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
.