Search code examples
reactjsrefreact-forwardref

Forward multiple ref to react children


I have seen some articles about forwardRef, however, I couldn't be able to find an example that have a specific case.

Which is: when I'm dealing with children props, I need to forward multiple ref to this children props.

I will give an example to clarify any doubt.

Let imagine, there is a parent component List, which will look like this:

const List = ({  children }) => (
  <div>
   {children}
  </div>
);

And we have its children component Tab:

const Tab = ({ children }) => (
  <div>
    {children}
  </div>
);

They are being used like that:

<List>
 <Tab />
 <Tab />
 <Tab />
</List>

Therefore my question is, how I would be able to create multiple refs at List, be able to forward them to Tab, properly set them at each Tab, and them finally get its reference at List to work with.

If there still any doubts I'm happy to clarify.


Solution

  • I guess you can use something like React.cloneElement and pass the references as props to the children.

    {React.Children.map(children, childElement =>
        React.cloneElement(childElement)
    )}