react-hook-form
을 사용하면서
Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
이런 에러를 만나게 됐는데, react-hook-form
이 ref를 자식컴포넌트에 전달하기 때문에 발생한 에러였다.
ref는 인스턴스에 접근하여 직접적으로 자식 데이터를 읽고 수정하는 게 가능하도록 한다. 하지만react props는 ref를 전달하지 못한다. 대표적인 Key값과 동일하게 props로 사용할 수 없다.
React에서 ref를 props로 사용하려면 forwardRef
를 사용해 자식요소로 ref
를 전달할 수 있다.
자식 컴포넌트를 forwardRef()함수로 감싸주고, props와 ref를 받아 사용할 수 있다.
const Input = forwardRef((props, ref) => {
return <input ref={ref} />;
});
추가로 eslint 에러나 개발자 도구에서 forwardRef사용시 이름이 나오지 않는 에러는
displayName 속성에 이름을 설정하거나, 익명함수 대신 이름있는 함수를 넘겨 주면 된다.
Input.displayName = "Input";
const Input = forwardRef(function Input(props, ref) {
return <input ref={ref} />;
});