JS' 공부흔적

[React] 함수 컴포넌트에 ref를 넘겨주고 싶다면? forwardRef()! 본문

React

[React] 함수 컴포넌트에 ref를 넘겨주고 싶다면? forwardRef()!

이준수 2023. 8. 12. 17:04

최근 합류한 사이드 프로젝트의 코드를 테스트하던 중 아래와 같은 Warning을 발견했다.

Warning: Function components cannot be given refs. Did you mean to use React.forwardRef()?

 

함수 컴포넌트에는 ref가 존재하지 않는데, forwardRef()를 쓰려고 했던 것이 아니냐는 Warning이었다. 해당 부분 코드를 확인해보니 자식 컴포넌트에 쓰이는 ref를 부모 컴포넌트에서 관리하고 있었다. 대략적인 코드를 보자.

// CalendarContainer.jsx (부모 컴포넌트)

const CalendarContainer = ({ type }) => {
  const calendarRef = useRef(null);
  ...
  return (
    ...
    <CustomCalendar
      calendarRef={calendarRef}
      ...
    />
    ...
  );
};
// CustomCalendar.jsx (자식 컴포넌트)

const CustomCalendar = ({
  calendarRef,
  ...
}) => (
	...
	<FullCalendar
		ref={calendarRef}
		...
	/>
	...
);

위처럼 CustomCalendar에서 쓰이는 calendarRef를 CalendarContainer에서 선언하고, 이를 CustomCalendar로 넘겨주고 있었다. 그러나 이때 발생하는 Warning에서 보여주듯이 함수 컴포넌트에는 ref가 존재하지 않는다. 이는 함수 컴포넌트가 인스턴스를 갖지 않기 때문인데, 이에 대해서는 따로 포스팅하겠다. 아무튼 CustomCalendar는 함수 컴포넌트이므로 ref를 전달할 수 없다. 이를 해결하기 위해서는 forwardRef를 사용하면 된다!

const SomeComponent = forwardRef(render)

공식 문서를 확인해보니 render 함수를 forwardRef로 감싸면 된다고 나와있다. 이때 render 함수는 props와 ref 파라미터를 갖고 있는데, props는 부모 컴포넌트가 넘겨준 props이고, ref는 부모 컴포넌트가 넘겨준 ref를 의미한다. 이를 통해 CustomCalendar 컴포넌트를 아래와 같이 수정할 수 있다.

// CustomCalendar.jsx (자식 컴포넌트)

import React, { forwardRef } from "react";

const CustomCalendar = forwardRef(
  (
    {
   	  ...
    },
      calendarRef,
  ) => (
    ...
    <FullCalendar
      ref={calendarRef}
      ...
     />
    ...
  ),
);

export default CustomCalendar;

 

부모 컴포넌트인 CalendarContainer에서는 아래처럼 calendarRef가 아닌 ref로 넘겨주면 된다.

// CalendarContainer.jsx (부모 컴포넌트)

const CalendarContainer = ({ type }) => {
  const calendarRef = useRef(null);
  ...
  return (
    ...
    <CustomCalendar
      ref={calendarRef}
      ...
    />
    ...
  );
};

 

Warning이 깔끔하게 사라졌다!

728x90
반응형