DEV Community

Srikanth Kyatham
Srikanth Kyatham

Posted on • Edited on

4 5

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.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay