Imagine having React component
function List() {
return (<ul>
<li>1</li>
<li>2</li>
</ul>
);
}
I would like to create high-order component which modifies, for example, styles of all li
node.
function makeRed(component) {
return function(props) {
const element = React.createElement(component, props);
return React.cloneElement(
element,
element.props,
React.Children.map(
element.props.children,
ch => React.cloneElement(ch, {
...ch.props,
style: {
backgroundColor: "red"
}
},
ch.props.children
)
)
);
}
}
But. This doesn't work. Children are empty.
Interesting that this works if I create component directly, like
...
const element = <ul><li>1</li><li>2</li></ul>;
...
Question: how to access a children and grandchildren of any React element?