프레임워크\라이브러리/React

[React] forwardRef란?

thinktank911 2025. 11. 25. 16:23

forwardRef() 란?

React 공식문서는, 일부 컴포넌트가 수신한 ref를 받아 조금 더 아래로 전달하는 Opt-in 기능이라고 소개한다.
React 컴포넌트를 forwardRef() 메서드로 감싸면, 컴포넌트 함수는 추가적으로 두 번째 매개변수로 ref를 받을 수 있게 된다.


부모 컴포넌트가 자식 컴포넌트를 참조하기 위해 forwardRef() 가 적용된 예시

import { useRef, forwardRef } from "react";

const Input = forwardRef((props, ref) => {
    return <input type="text" ref={ref} />;
});

const Field = () => {
    const inputRef = useRef(null);
    const focusHandler = () => {
    	inputRef.current.foucus();
    };
    
    return( 
    	<> 
            <Input ref={inputRef} /> 
            <button onClick={focusHandler}>focus</button> 
        </> 
    ); 
};
  • 자식 컴포넌트(Input)를 React의 forwardRef() 로 감싼다. 두 번째 인자인 ref를 참조하려고 하는 엘리먼트에 할당한다.
  • 부모 컴포넌트(Field)에서 참조를 위한 useRef() 를 생성한다. (클래스형 컴포넌트의 경우엔 React.createRef())
  • 참조를 위한 ref값(inputRef)을 자식 컴포넌트의 props로 할당해준다. 별도의 에러가 발생하지 않는다.

참고 블로그 : https://abangpa1ace.tistory.com/entry/React-forwardRef-%EB%9E%80#google_vignette

 

 

[React] 자식 컴포넌트 제어 - forwardRef, useImperativeHandle

사이드 프로젝트에서 Uncontrolled Input을 구현하기 위해 고민하던 중, 문득 자식(input)의 ref.current.value를 부모(container component)가 어떻게 참조할 수 있을까에 대한 의문이 생겼다. * ref, useRef() 포스팅

abangpa1ace.tistory.com