In short in this post, I want to show how to forward refs if its needs to be passed more than one level
In the React forwardRef guide the instructions tell us how to pass one level. How about if needs to be passed more than one level.
In my case it was a custom button
const LinkButton = (props) => {
return <button {...props} />;
}
I had to use this button inside another component which was passing ref to this button.
The usage was
const ShowInfoBox = () => {
const infoRef = React.useRef(null);
const props = {};
return (
<InfoBox
referenceElement={<LinkButton {...props} />}
ref={infoRef}
>
{content}
</InfoBox>
);
}
When I used like above the React complained
Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
To solve this I had to create a wrapper component
const LinkButtonWithRef = React.forwardRef((props, ref) => (
<LinkButton {...props} ref={ref} />
));
Since I cannot use the prop with name "ref", I had to rename to "innerRef". The subsequent changes were
const LinkButton = ({innerRef, ...rest}) => {
return <button ref={innerRef} {...rest} />;
}
const LinkButtonWithRef = React.forwardRef((props, ref) => (
<LinkButton {...props} innerRef={ref} />
));
Hope it helps someone who is facing similar issue.
Top comments (0)