HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptreactCritical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
parentupdatethereactstatecanhow

Problem

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 
  }
}

class Child extends React.Component {
  render() {
    return 
  }
}


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.

Code Snippets

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}/ >
  }
}

Context

Stack Overflow Q#35537229, score: 925

Revisions (0)

No revisions yet.