Post

forwardRef 사용하기

오류 나는 경우

리액트에서 ref를 props로 전달하기 위해서는 forwardRef를 사용해야 한다.

forwardRef를 사용하지 않고 자식에게 ref를 전달하면 아래와 같은 에러가 발생한다.

1
2
3
4
5
6
7
8
9
10
// App.jsx
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;

// FancyButton.jsx
const FancyButton = ({ ref }) => {
  <button ref={ref} className="FancyButton">
    {props.children}
  </button>;
};

올바른 예

JSX를 forwardRef로 감싸주고, 두 번째 파라미터로 ref를 전달한다.

1
2
3
4
5
6
7
8
9
10
11
// App.jsx
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;

// FancyButton.jsx
// forwardRef 두 번째 인자로 ref를 받는다.
const FancyButton = React.forwardRef((props, ref) => (
  <button ref={ref} className="FancyButton">
    {props.children}
  </button>
));

참고사이트

Forwarding Refs

This post is licensed under CC BY 4.0 by the author.