Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Output each child with a wrapper from React.Children array

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading