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?
Some reason React.children was not working for me. This is what worked for me.
I wanted to just add a class to the child. similar to changing a prop
The trick here is the React.cloneElement. You can pass any prop in a similar manner
Try this
It worked for me using react-15.1.
With the update to React 16.6 you can now use React.createContext and contextType.
You can use
React.cloneElement
, it's better to know how it works before you start using it in your application. It's introduced inReact v0.13
, read on for more information, so something along with this work for you:So bring the lines from React documentation for you to understand how it's all working and how you can make use of them:
more here...
Further to @and_rest answer, this is how I clone the children and add a class.
Parent.jsx:
Child.jsx:
and main.jsx:
see example here: https://plnkr.co/edit/jJHQECrKRrtKlKYRpIWl?p=preview