javascriptreactjsweb-deployment

How can I update the parent's state in React?


My 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 its state in Component 1 and forward it, right? And yes, I've read about Redux, but I don't want to use it. I hope that it's possible to solve it just with react. Am I wrong?


Solution

  • 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() {
        this.setState({
          someVar: 'some value'
        })
      }
    
      render() {
        return <Child handler = {this.handler} />
      }
    }
    
    class Child extends React.Component {
      render() {
        return <Button onClick = {this.props.handler}/ >
      }
    }
    
    

    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.