forwardRef는 부모 컴포넌트에서 자식 컴포넌트의 ref를 다루고 싶을 때 사용합니다. 리액트에서는 자식 컴포넌트의 값을 부모로 올리는 것이 어려우므로 ref를 부모 컴포넌트에서 만들어서 자식에게 내려보내주어야 합니다.
React Component를 forwardRef() 함수로 감싸주면, 컴포넌트 함수는 2번째 매개변수를 갖게 되는데 이를 통해 ref prop을 넘길 수 있습니다.
import { useRef, forwardRef } from "react";
const Children = forwardRef((props, ref) => {
return <input type="text" ref={ref} />;
});
const Parent = () => {
const inputRef = useRef(null);
const focusHandler = () => {
inputRef.current.foucus();
};
return(
<>
<Children ref={inputRef} />
<button onClick={focusHandler}>focus</button>
</>
);
};
Component를 forwardRef()로 감싸주고, 2번째 매개변수로 ref를 받아 컴포넌트에 ref를 prop을 넘겼더니
Warning: Input: ref
is not a prop. Trying to access it will result in undefined
being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)
위의 경고 메세지 없이 버튼을 클릭하면 input에 포커스가 된 것을 확인할 수 있습니다.
참고
https://www.zerocho.com/category/React/post/5fa901f8c610950004a07e8d