본문 바로가기
IT/react

React - forward ref

by 내일은교양왕 2023. 6. 22.

요약
자식 컴포넌트에 ref prop을 react guide대로 넘겨주고 싶을 때 forwardRef 사용한다.

사례
보통 ref를 자식 컴포넌트에 prop으로 전달해주는 상황은 많지 않은데, 간혹 전달해주어야할 상황이 발생한다
ref를 prop으로 넘겼을 때 jsx syntax 에러가 발생한다.
이유는 ref는 React에서 특수한 목적으로 사용되는 prop이라 일반적인 용도로 개발자가 사용할 수 없다. (key도 마찬가지)

Warning: Input: `ref` is not a prop. Trying to access it will result in `undefined` being returned.
If you need to access the same value within the child component, you should pass it as a different prop.
(https://reactjs.org/link/special-props)

 

해결 방법
해결하는 방법은 2가지가 있다.

Prop key 변경
prop key를 ref로 설정하지 말고 ref1, 또는 ref2로 ref외 다른 naming으로 한다.
그리 좋은 방법은 아닙니다.

ForwardRef 사용
아주 깔끔하죠?

 

const Editor = forwardRef((props, ref) => {
  return <div ref={ref} />
})


참고
DaleSeo - [React] forwardRef 사용법
reactjs.org - Ref 전달하기

'IT > react' 카테고리의 다른 글

React - Error: ReactDOMServer does not yet support Suspense.  (0) 2023.06.22
React - useCallback  (0) 2023.06.22
React - memo  (0) 2023.06.22
React - flushsync  (0) 2023.06.22
React - Virtual Dom  (0) 2023.06.22