React transferring props to many child components

In react components sometimes ( or often ) We have situation when we encapsulating many child components which for sure can have many properties. This article is discussing how send properties from parent component to its many children.

To explain problem We need some example. So parent component has structure ( in render ):

<div>
<ChildComponent1></ChildComponent1>
<ChildComponent2></ChildComponent2>
</div>

So how set props to ChildComponent1 and ChildComponent2? First and easiest is to create all properties in parent and set it to children.

<div>
<ChildComponent1 prop1={this.prop1} prop2={this.prop2} ></ChildComponent1>
<ChildComponent2 prop1={this.prop3} prop2={this.prop4}></ChildComponent2>
</div>

But in this solution we need to set all properties in Parent component and laboriously paste it in childs. It is not quite good solution when components has many properties, it is ok only when We have few props.

In react documentation we have some information about transferring props –  https://facebook.github.io/react/docs/transferring-props.html. So we can use it …other from ES6. Wait a moment.. we have many children components, how to avoid overlaping props and how We can have separation of Parent and every Children props?

The best solution is to create sub-objects inside Parent props. So we can create something like ( Parent code – props types declaration ):

Parent.propTypes = {
child1:React.PropTypes.object,
child2::React.PropTypes.object
};

And use it in render method ( Parent code ):

<div>
<ChildComponent1 {...this.props.child1} ></ChildComponent1>
<ChildComponent2 {...this.props.child2} ></ChildComponent2>
</div>

Every object property used in Parent component in child1 or child2 will be assigned to children components. This solution encapsulates props in childrens without doing operations in one big list of properties.

Last thing is setting properties in Parent component which will be populated to children components ( render code of component using Parent component ):

<Parent child1={{someProp:"someValue"}} child2={{someProp:"someValue"}} />

Remember props can be nested structures so We can have encapsulated properties for every child component.