[React] ref를 prop으로 넘기기 - forwardRef()

bunny.log·2023년 5월 17일
0

forwardRef

forwardRef는 부모 컴포넌트에서 자식 컴포넌트의 ref를 다루고 싶을 때 사용합니다. 리액트에서는 자식 컴포넌트의 값을 부모로 올리는 것이 어려우므로 ref를 부모 컴포넌트에서 만들어서 자식에게 내려보내주어야 합니다.

ref prop을 사용하려면 forwardRef()라는 함수를 사용해야 한다.

React Component를 forwardRef() 함수로 감싸주면, 컴포넌트 함수는 2번째 매개변수를 갖게 되는데 이를 통해 ref prop을 넘길 수 있습니다.

forwardRef() 사용하기

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에 포커스가 된 것을 확인할 수 있습니다.

Callback Ref

참고
https://www.zerocho.com/category/React/post/5fa901f8c610950004a07e8d

참고
https://dori-coding.tistory.com/entry/React-ref%EB%A5%BC-prop%EC%9C%BC%EB%A1%9C-%EB%84%98%EA%B8%B0%EA%B8%B0-forwardRef

profile
더 많은 유익한 내용은 ->> https://github.com/nam-yeun-hwa

0개의 댓글