I'm trying to find the proper way to define some components which could be used in a generic way:
<Parent>
<Child value="1">
<Child value="2">
</Parent>
There is a logic going on for rendering between parent and children components of course, you can imagine <select>
and <option>
as an example of this logic.
This is a dummy implementation for the purpose of the question:
var Parent = React.createClass({
doSomething: function(value) {
},
render: function() {
return (<div>{this.props.children}</div>);
}
});
var Child = React.createClass({
onClick: function() {
this.props.doSomething(this.props.value); // doSomething is undefined
},
render: function() {
return (<div onClick={this.onClick}></div>);
}
});
The question is whenever you use {this.props.children}
to define a wrapper component, how do you pass down some property to all its children?
None of the answers address the issue of having children that are NOT React components, such as text strings. A workaround could be something like this:
According to the documentation of
cloneElement()
So cloneElement is what you would use to provide custom props to the children. However there can be multiple children in the component and you would need to loop over it. What other answers suggest is for you to map over them using
React.Children.map
. HoweverReact.Children.map
unlikeReact.cloneElement
changes the keys of the Element appending and extra.$
as the prefix. Check this question for more details: React.cloneElement inside React.Children.map is causing element keys to changeIf you wish to avoid it, you should instead go for the
forEach
function likeIs this what you required?
The slickest way to do this:
Pass props to direct children.
See all other answers
Pass shared, global data through the component tree via context
Disclaimer: This is an updated answer, the previous one used the old context API
It is based on Consumer / Provide principle. First, create your context
Then use via
and
Full example, semi-pseudo code.
1 https://facebook.github.io/react/docs/context.html
If you have multiple children you want to pass props to, you can do it this way, using the React.Children.map:
If your component is having just one child, there's no need for mapping, you can just cloneElement straight away: