reactjsrefreact-forwardref

Forward multiple ref to react children


I have seen some articles about forwardRef, however couldn't be able to find an example that have a specific approach to it, basically when we are dealing with the children props of React and we need to forward multiple ref to this children props.

I will give an example to clarify any doubt.

Let image we have a parent component List, which will look like it:

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)
    )}