Reactjs - passing state value from one component to another

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.

Code snippet

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.

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


You can only pass props from parent to child component. Either restructure your components hierarchy to have this dependence, or use a state/event management system like Redux (react-redux) .