
Adding props or functionality to React children
For most cases to render children you can use this.props.children
render() {
return (
<div>
{this.props.children}
</div>
)
}
However, if you wanted to add functionality like an onClick handler to the children you can map through the children and clone them with the extra props.
Let's say you start with this:
render() {
return(
<ShoppingList>
<Item>First</Item>
<Item>Second</Item>
<Item>Third</Item>
</Shopping>
)
}
And you wanted to add an onclick to each item. Then you can use React.Children.map API and add it to each child using the React.cloneElement React API. Note the React.Children.map works differently than a typical ES6 .map. As its first argument it takes in the array that it will map through and the 2nd argument is the function applied to each element.
render() {
return (
<div>
{React.Children.map(this.props.children, child => {
return React.cloneElement(child, {
onClick: this.props.onClick })
})}
</div>
)
}
The arguments in the function applied to each element are (the_children_element, the_props_you_want_to_add_to_it).
Leave Adding props or functionality to React children to:
Read more #react posts
Best Posts From positivelyzack
We have not curated any of positivelyzack's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.
More Posts From positivelyzack
- Adding props or functionality to React children
- Positive Product Design
- Half Life: The Decay of Utility of Software Knowledge or why you should learn to learn
- Pure Functions
- Deploying a fullstack React app to Heroku
- Components with Props In React
- The structure of app created with the create-react-app tool.
- ES6 Javascript exports, imports and the difference between 'default export' & 'export'