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:
Here is the sample:
const Child = ({ doSomething, value }) => (
<div onClick={() => doSomething(value)}>Click Me</div>
);
class Parent extends React.PureComponent {
doSomething = (value) => {
console.log('doSomething called by child with value:', value);
}
render() {
const { children } = this.props;
var childrenWithProps = React.Children.map(children, child => React.cloneElement(child, { doSomething: this.doSomething }));
return <div>{childrenWithProps}</div>
}
};
ReactDOM.render(
<Parent>
<Child value="1" />
<Child value="2" />
</Parent>,
document.getElementById('container')
);
https://jsfiddle.net/2q294y43/2/
You can use [React.Children][1] to iterate over the children, and then clone each element with new props (shallow merged) using [React.cloneElement][2] e.g:
const Child = ({ doSomething, value }) => (
<div onClick={() => doSomething(value)}>Click Me</div>
);
class Parent extends React.PureComponent {
doSomething = (value) => {
console.log('doSomething called by child with value:', value);
}
render() {
const { children } = this.props;
var childrenWithProps = React.Children.map(children, child =>
React.cloneElement(child, { doSomething: this.doSomething }));
return <div>{childrenWithProps}</div>
}
};
ReactDOM.render(
<Parent>
<Child value="1" />
<Child value="2" />
</Parent>,
document.getElementById('container')
);
Fiddle: https://jsfiddle.net/2q294y43/2/
[1]: https://facebook.github.io/react/docs/react-api.html#react.children
[2]: https://facebook.github.io/react/docs/react-api.html#cloneelement