Sometimes, we want to avoid ‘Function components cannot be given refs’ when using react-router-dom.
In this article, we’ll look at how to avoid ‘Function components cannot be given refs’ when using react-router-dom.
How to avoid ‘Function components cannot be given refs’ when using react-router-dom?
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 to the ref
prop of a component inside NavLink
.
Conclusion
To avoid ‘Function components cannot be given refs’ when using react-router-dom, we can use the React.forwardRef
method.