Reactjs - passing state value from one component to another

折月煮酒 提交于 2019-12-05 03:25:10

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) .

I had the same issue with parent and child components and the solution was simply send down the function (which is altering the state in the parent component) as a prop to the child component. In this way both are sharing that particular variable's state. Hope this straightforward approach helps you!

I believe keeping the status values aligned with the page URL is another good way, not only to pass values, but also to keep the page status controllable with urls.

Imagine that you are building an advanced search page, where different components will control the search criteria, hence, in addition to search functionality, user should be able to keep his search settings by the used URL.

Supposing that clicking on a link in component x adds a query string criteria1=x to the current page url, and so on for the other components. Let's say we have also configured the search functionality to depend on the URL to read state values from it, this way, you will be able to pass values from a specific component to any number of components without restrictions.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!