next-routes icon indicating copy to clipboard operation
next-routes copied to clipboard

Error using Link component "Warning: Function components cannot be given refs."

Open RileySpiller opened this issue 5 years ago • 1 comments

Has anyone run into this console error?

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

My code is:

<Link>
  <CustomStyledAComponent>Test</CustomStyledAComponent>
</Link>

RileySpiller avatar Jun 16 '20 20:06 RileySpiller

Yes. You need to use React's forwardRef function in the CustomStyledAComponent like so:

const CustomStyledAComponent = React.forwardRef((props, ref) => (
  <div ref={ref}>
    {props.children}
  </div>
));

As Link wants to pas a ref to the child component in order to do link stuff, you need to forward the ref to the inner component which in the example is the div.

chrisneven avatar Jun 18 '20 10:06 chrisneven