JavaScript

[react] forwardRef

유병각 2022. 3. 2. 08:16

Forward Ref

useRef 를 사용해 엘리먼트를 참조할 때, ref 를 자식 컴포넌트에게 props 로 전달 할 수 없다.

export default function Children(props) {
  const ref = props.ref; // 에러발생
  console.log(ref); // 에러발생
  return <button>클릭</button>;
}

이때 forward ref 를 사용하면, 부모에서 정의한 ref 로 자식의 엘리먼트를 참조 할 수 있다!!

(참고로 forwarding 은 전송이라는 뜻이며 즉, ref 를 자식 컴포에게 전송한다 라는 의미이다.)

코드

부모컴포넌트

import { ConstTypeChild } from "./ConstTypeChild";
import FunctionTypeChild from "./FunctionTypeChild";
import { useRef, useState, useEffect } from "react";

export default function Parent() {
  const constref = useRef();
  const functionref = useRef();
  const [toggle, setToggle] = useState([false]);
  const onClick = () => {
    setToggle(!toggle);
  };

  useEffect(() => {
    if (toggle) {
      constref.current.style = "width:300px; height:300px; background:red;";
      functionref.current.style = "width:300px; height:300px; background:red;";
    } else {
      constref.current.style = "width:300px; height:300px; background:blue;";
      functionref.current.style = "width:300px; height:300px; background:blue;";
    }
  }, [toggle]);

  return (
    <>
      <FunctionTypeChild onClick={onClick} ref={constref}></FunctionTypeChild>
      <ConstTypeChild onClick={onClick} ref={functionref}></ConstTypeChild>
    </>
  );
}

Child1 (Const Type)

import { forwardRef } from "react";

const ConstTypeChild = forwardRef((props, ref) => {  
const onClick = props.onClick;  
return (  
<button ref={ref} onClick={() => onClick()}>  
constTypeButton  

);  
});  
ConstTypeChild.displayName = "ConstTypeChild";  
// 리액트 컴포넌트 디버깅 툴로 봤을때 이 코드가  
// 없으면 컴포 이름이 forwarding ref 로 뜸  
export { ConstTypeChild };

Child2 (function Type)

import { forwardRef } from "react";

function FunctionTypeChild(props, ref) {  
const onClick = props.onClick;  
return (


FunctionType  


);  
}

FunctionTypeChild = forwardRef(FunctionTypeChild);  
// 리액트 컴포넌트 디버깅 툴로 봤을때 이 코드가  
// 없으면 컴포 이름이 forwarding ref 로 뜸  
export default FunctionTypeChild;

reference

https://github.com/gaki2/forwarding-refs
https://en.reactjs.org/docs/forwarding-refs.html