How can I pass props/context to dynamic childrens in react?

javascript, reactjs

Solution

There's not a a great way to do this that is clear and passing all the properties of the parent isn't a great pattern and could lead to some very difficult to follow code if not done carefully (and with excellent documentation). If you have a subset of properties though, it's straightforward:

JsFiddle

Assuming you're using React with Addons, you can clone the children of a React component and set new property values on them. Here, the code just copies a property called `parentValue` into each child. It needs to create a clone of each element as the child element had already been created.

var Hello = React.createClass({
    render: function() {
        var self = this;
        var renderedChildren = React.Children.map(this.props.children,
            function(child) {
                // create a copy that includes addtional property values
                // as needed
                return React.addons.cloneWithProps(child, 
                    { parentValue: self.props.parentValue } );                
            });
        return (<div>
            { renderedChildren }            
        </div>)
        ;
    }
});

var SimpleChild = React.createClass({
    render: function() {
        return <div>Simple { this.props.id }, from parent={ this.props.parentValue }</div>
    }
});

React.render((<Hello parentValue="fromParent">
    <SimpleChild id="1" />
    <SimpleChild id="2" />
</Hello>), document.body);

Produces:

Simple 1, from parent=fromParent
Simple 2, from parent=fromParent

Problem

I am using react, and I am trying to pass props/context to my dynamic childrens, by dymamic childrens I mean childrens are render using ``` {this.props.children} ``` How can I pass to this children (In my code I know it's type) context/props? In this jsbin there is an example that it dosen't work on dynamic childrens. http://jsbin.com/puhilabike/1/edit?html,js,output

Original source