Home > Blockchain >  Forward multiple ref to react children
Forward multiple ref to react children

Time:12-16

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.

CodePudding user response:

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

CodePudding user response:

This is the current answer I came with:

const tabReferences = React.useRef<HTMLDivElement>([]);

... 

{React.Children.map(children, (child, index) => {
  return React.cloneElement(child, {
       ref: tabReferences.current[index],
  });
})}

Thanks Lucas!

  • Related