React 컴포넌트에 ref prop을 넘겨서 그 내부에 있는 HTML Element에 접근을 하게 해주는 forwardRef() 함수에 대해서 알아보겠습니다.

HTML Element ref prop

React에서 ref prop은 HTML Element의 직접 접근하기 위해서 사용됩니다.

예를 들어, 아래 <Filed/> 컴포넌트에서는 useRef hook 함수로 생성한 inputRef 객체를 <input/> 엘리먼트 의 ref prop으로 넘기고 있습니다.

이렇게 해주면 inputRef 객체의 current 속성에 <input/> 엘리먼트의 레퍼런스가 할당되는데, 이를 통해 handleFocus() 이벤트 핸들러에서 <input/> 엘리먼트의 focus() 함수를 호출할 수 있습니다.

import React, { useRef } from "react";

function Field() {
  const inputRef = useRef(null);

  function handleFocus() {
    inputRef.current.focus();
  }

  return (
    <>
      <input type="text" ref={inputRef} />
      <button onClick={handleFocus}>입력란 포커스</button>
    </>
  );
}

React 컴포넌트의 ref prop

어떤 컴포넌트에서 다른 컴포넌트 내부에 있는 HTML Element에 직접 접근해야할 때가 종종 있는데요.

예를 들어, 위 <Field/> 컴포넌트로 부터 <input/> 엘리먼트를 별도의 <Input/> 컴포넌트로 빼내보겠습니다.

먼저 부모인 <Field/> 컴포넌트는 useRef() hook 함수로 생성한 inputRef 객체를 자식인 <Input/> 컴포넌트에 ref prop으로 넘김니다. 그러면 자식인 <Input/> 컴포넌트는 이 ref prop으로 넘어온 inputRef 객체를 다시 내부에 있는 <input/> 엘리먼트의 ref prop으로 넘겨줍니다.

import React, { useRef } from "react";

function Field() {
  const inputRef = useRef(null);

  function handleFocus() {
    inputRef.current.focus();
  }

  return (
    <>
      <Input ref={inputRef} />
      <button onClick={handleFocus}>입력란 포커스</button>
    </>
  );
}

function Input({ ref }) {
  return <input type="text" ref={ref} />;
}