Want to pass state value from one component to another in Reactjs? If you have to pass state from Dashboard to Sidebar, you have to render Sidebar from Dashboard’s render function. Here, you can pass the state of Dashboard to Sidebar.
1 2 3 4 5 6 7 8 9 | class Dashboard extends Component { ... ... render(){ return( <Sidebar data={this.state.data1}/> ); } } |
If you want the changes made on props (data1) passed to Sidebar be received by Dashboard, you need to lift the state up. i.e, You have to pass a function reference from Dashboard to Sidebar. In Sidebar, you have to invoke it whenever you want the data1 to be passed back to Dashboard. Code snippet.
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 | class Dashboard extends Component { constructor(props){ ... //following is not required if u are using => functions in ES6. this.onData1Changed = this.onData1Changed.bind(this); } ... ... onData1Changed(newData1){ this.setState({data1 : newData1}, ()=>{ console.log('Data 1 changed by Sidebar'); }) } render(){ return( <Sidebar data={this.state.data1} onData1Changed={this.onData1Changed}/> ); } } class Sidebar extends Component { ... //whenever data1 change needs to be sent to Dashboard //note: data1 is a variable available with the changed data this.props.onData1changed(data1); } |
Reference Doc: https://facebook.github.io/react/docs/lifting-state-up.html
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.