Categories
React Answers

How to avoid ‘Function components cannot be given refs’ when using React react-router-dom?

Spread the love

To avoid ‘Function components cannot be given refs’ when using react-router-dom, we can use the React.forwardRef method.

For instance, we write

const MyLink = React.forwardRef((props, ref) => (
  <NavLink innerRef={ref} {...props} />
));

to call React.forwardRef with a callback that renders the NavLink component.

We pass in the ref into the NavLink component as the value of the innerRef prop.

And then we can assign the innerRef prop of a component inside NavLink to get the ref that we pass in as the value of the ref prop of MyLink.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *