도도다다

nextjs: <Link /> Function components cannot be given refs. Attempts to access this ref will fail.

2021. 6. 20. 21:48 | 개발 관련

Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

Next.js 10에서 컴포넌트를 사용하던 도중 이런 오류가 발생했다.

문제 이유

<Link href="/href">
  <Button
      type="custom"
      color="#FCFCFC"
  >
    buttonText
  </Button>
</Link>

상단에 적은 예제처럼, Link의 children으로 컴포넌트를 줘서 그런거라고. 내가 작성한 코드를 가져올 순 없어서 다른 예제를 가져왔다.

해결

Link의 children에 a 태그를 사용하면 된다.

<Link href="/href">
  <a>
      <Button
      type="custom"
      color="#FCFCFC"
    >
      buttonText
    </Button>
  </a>
</Link>

Button 상에서 사용하던 요소를 a에서 div로 변경해주고 난 후에, 컴포넌트 상위를 a 태그로 감싸주었다.

refs