How to update parent's state in React?


#1

y structure looks as follows:

Component 1  

 - |- Component 2


 - - |- Component 4


 - - -  |- Component 5  

Component 3

Component 3 should display some data depending on state of Component 5. Since props are immutable, I can’t simply save it’s state in Component 1 and forward it, right? And yes, I’ve read about redux, but don’t want to use it. I hope that it’s possible to solve it just with react. Am I wrong?


#2

For child-parent communication you should pass a function setting the state from parent to child, like this

class Parent extends React.Component {
  constructor(props) {
    super(props)

    this.handler = this.handler.bind(this)
  }

  handler(e) {
    e.preventDefault()
    this.setState({
      someVar: someValue
    })
  }

  render() {
    return <Child handler = {this.handler} />
  }
}

class Child extends React.Component {
  render() {
    return <Button onClick = {this.props.handler}/ >
  }
}

Run code snippet

Expand snippet

This way the child can update the parent’s state with the call of a function passed with props.

But you will have to rethink your components’ structure, because as I understand components 5 and 3 are not related.

One possible solution is to wrap them in a higher level component which will contain the state of both component 1 and 3. This component will set the lower level state through props.