내가 해결한 오류들

(해결됨) Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

홍구리당당 2023. 12. 31. 20:33

 

ref 객체는 자식에게 내려줄 수 없다. 그래서 가끔 자식에게 ref 객체를 넘겨주려 할 때 다음과 같은 에러가 나타난다.

문제 상황...

// A component

export default A(){
      const ref = useRef( ... );

    return <B ref={ref}/>
}
// B component

export default B(){
      return (
      // 에러 발생!!
          <input type="text" ref={ref}/>
    );
}

이렇게 다른 컴포넌트로 ref를 넘겨주려면 해당 컴포넌트를 forwardRef 메소드로 만들어야 한다.

문제 해결방법...

// B component를 다음과 같이 선언하자. 
const B = React.forwardRef( ref) => {
    return (
        <input type="text" ref={ref}/>

    );
});

그런데 가끔 이렇게 쓰면 eslint에 걸려서 Component definition is missing display name 에러가 나기도 한다.

displayName을 명시하면 문제는 해결된다!!

문제 해결 최종본

// B component를 다음과 같이 선언하자. 
const B = React.forwardRef( ref) => {
    return (
        <input type="text" ref={ref}/>

    );
})

B,displayName = "B"; // displayName을 컴포넌트 이름과 다르게 지어도 되지만 보통은 똑같이 짓는다.