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?
I needed to fix accepted answer above to make it work using that instead of this pointer. This within the scope of map function didn't have doSomething function defined.
Update: this fix is for ECMAScript 5, in ES6 there is no need in var that=this
For a slightly cleaner way to do it, try:
Note: this will only work if there is a single child, and it is a valid React element.
Cleaner way considering one or more children
Maybe you can also find useful this feature, though many people have considered this as an anti-pattern it still can be used if you're know what you're doing and design your solution well.
Function as Child Components
You no longer need
{this.props.children}
. Now you can wrap your child component usingrender
inRoute
and pass your props as usual:You can use React.Children to iterate over the children, and then clone each element with new props (shallow merged) using React.cloneElement e.g:
Fiddle: https://jsfiddle.net/2q294y43/2/