Want to pass props to a component passed as prop in React? You can achieve that by using React.cloneElement.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
class Parent extends React.Component{ render() { return( <Child a={1} comp={<GChild/>} /> ) } } class Child extends React.Component{ constructor(){ super(); this.state = {b: 1}; this.updateB = this.updateB.bind(this); } updateB(){ this.setState(prevState => ({b: prevState.b+1})) } render(){ var Comp = this.props.comp; return ( <div> {React.cloneElement(Comp, {b: this.state.b})} <button onClick={this.updateB}>Click to update b</button> </div> ); } } const GChild = props => <div>{JSON.stringify(props)}</div>; ReactDOM.render( <Parent />, document.getElementById('container') ); |
1 2 3 4 |
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id='container' /> |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.