DEV Community

Srikanth Kyatham
Srikanth Kyatham

Posted on • Updated on

Passing React.forwardRef to child's child

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} />;
}
Enter fullscreen mode Exit fullscreen mode

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>
  );
}
Enter fullscreen mode Exit fullscreen mode

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} />
));
Enter fullscreen mode Exit fullscreen mode

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} />;
}
Enter fullscreen mode Exit fullscreen mode
const LinkButtonWithRef = React.forwardRef((props, ref) => (
  <LinkButton {...props} innerRef={ref} />
));
Enter fullscreen mode Exit fullscreen mode

Hope it helps someone who is facing similar issue.

Top comments (0)