Home > Mobile >  Output each child with a wrapper from React.Children array
Output each child with a wrapper from React.Children array

Time:09-08

I have this reusable component.

export const ListItems = ({ controls, children }) => {

const content = controls ? <PrivateComponent>{ children }</PrivateComponent> : children;

return <ul>{ content }</ul>

}

Seems pretty-straight forward. The idea is that, in PrivateComponent, I wanna wrap each of the children with an extra wrapper, something like this:

export const PrivateComponent = ({ children }) => {

const _children = React.Children.toArray(children);

return (

<div>{ _children.map(child => <SomeWrapper>{ child }</SomeWrapper> ) }</div>

);

}

My question is, is it correct to render child this way, or should I use cloneElement? Also, what should I use for the key of SomeWrapper in the map function?

CodePudding user response:

is it correct to render child this way, or should I use cloneElement?

You can use the child instance directly, there is no problem there. You need cloneElement only if you want to change / add any props or swap out its own children, or if you need a duplicate because you intend to insert "the same child" in two different location in your DOM.

what should I use for the key of SomeWrapper in the map function?

You can use React.Children.map(children, function[(thisArg)]) (doc) which will automatically add keys.

  • Related