HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
🧚
[1기]최종 프로젝트 데브코스
/
🏄‍♂️
[팀8] 어푸(Ah puh) - Surf
/
🔫
Trouble shooting
/
하위 함수형 컴포넌트에 ref를 줘야할 때

하위 함수형 컴포넌트에 ref를 줘야할 때

WHO
STATUS
solved
WHEN
Dec 9, 2021

👿 Problem

하위 컴포넌트의 HTML 엘리먼트에 직접 접근하기 위해 ref를 달았더니 경고가 떴다.
Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
ref는 HTML 엘리먼트에 접근하기 위해 사용되므로 일반적인 prop로 사용할 수 없다. ref를 하위 컴포넌트에 전달하기 위해선 forwardRef()를 사용해야 한다.

😇 Solution

  • ref를 전달할 부모 컴포넌트에선 하위 컴포넌트에 useRef로 ref를 전달한다.
const Parent = () => { const inputRef = useRef(null) return ( <Input ref={inputRef} /> ) } export default Parent
  • 하위 컴포넌트에선 ref를 두번째 인자로 받고 props를 받듯이 똑같이 진행하면 된다.
import React, { useEffect, forwardRef } from 'react' const Input = ( props, ref ) => { useEffect(() => { ref?.current.focus() }, [ref]) return ( <input ref={ref} /> ) } export default forwardRef(Input)
  • 다만 forwardRef를 export default 쪽으로 감쌀 경우 실제 React 컴포넌트의 이름을 숨기기 때문에 아래와 같은 디버깅 오류가 뜬다.
Warning: forwardRef render functions do not support propTypes or defaultProps. Did you accidentally pass a React component?
notion image
 
import React, { useEffect, forwardRef } from 'react' const Input = forwardRef(( props, ref ) => { useEffect(() => { ref?.current.focus() }, [ref]) return ( <input ref={ref} /> ) }) Input.displayName = 'Input' export default Input
따라서 export default 부분대신 함수 부분을 forwardRef()로 감싸주고 Input 컴포넌트의 displayName을 그대로 넣어주면 디버깅 오류를 없앨 수 있다.

🧐 Reference

[React] forwardRef 사용법
React 컴포넌트에 ref prop을 넘겨서 그 내부에 있는 HTML 엘리먼트에 접근을 하게 해주는 forwardRef() 함수에 대해서 알아보겠습니다. React에서 ref prop은 HTML 엘리먼트의 직접 접근하기 위해서 사용됩니다. 예를 들어, 아래 컴포넌트에서는 useRef() 훅(hook) 함수로 생성한 inputRef 객체를 엘리먼트의 ref prop으로 넘기고 있습니다.
[React] forwardRef 사용법
https://www.daleseo.com/react-forward-ref/
Using forwardRef with proptypes and eslint
I am trying to use forwardRef for a Button in a project using eslint and prop-types. This is what I tried so far, and the errors I get each time: function Button ({ action = { callback: () => {}, title: 'unknown' } }, ref) { return ( {action.icon || action.title} ) } Button.propTypes = { action: Action.isRequired } export default forwardRef(Button) This will give me the following warning in the console: Warning: forwardRef render functions do not support propTypes or defaultProps.
Using forwardRef with proptypes and eslint
https://stackoverflow.com/questions/59716140/using-forwardref-with-proptypes-and-eslint
Using forwardRef with proptypes and eslint