I have a Component that renders all the children passed to it as list elements. For example:
// more or less the logic of my component
const ListifyChildren = (props) => {
return <ul>{props.children.map(element => <li>{element}</li>)}</ul>
}
// example use
<ListifyChildren>
<div>Some component</div>
<div>Some other component</div>
</ListifyChildren>
Would produce
<ul class="listify">
<li class="listify-list-item">Some component</li>
<li class="listify-list-item">Some other component</li>
</ul>
But the problem is I want to be able to use HoC's that return a list of components and to treat those components as children of my actual list. For example:
const ReturnSomeStuff = () => {
return [someArray].map(element => <div>{element}</div>
}
<ListifyChildren>
<ReturnSomeStuff/>
</ListifyChildren>
//what I get:
<ul class="listify">
<li class="listify-list-item">
<div>something</div>
<div>something</div>
<div>something</div>
</li>
</ul>
//what I want to get:
<ul class="listify">
<li class="listify-list-item">something</li>
<li class="listify-list-item">something</li>
<li class="listify-list-item">something</li>
</ul>
How can I make sure that my component maps over actual html children, not the function calls passed to it?
You can use Fragment to do it: https://reactjs.org/docs/fragments.html
const ReturnSomeStuff = () => {
return [someArray].map(element => <>{element}</>
}
I have found the answer: the key is referring to child elements via React.Children API rather than simple props.children - it returns the list of rendered elements.