1

If I have a parent that sets a state and passes it to a child, how can I change the state of the parent FROM the child?

    // parent
    this.state = {
        status: 'doing...'
    }

    // child render
    <div>{this.props.state.status}</div>
    // child function triggered by an onClick
    update = () => this.setState(status: 'finished');

Something like this doesn't work

    // parent
    this.state = {
        status: this.props.state.status
    }

    // or child
    this.props.setState(status: 'finished');

    // or child
    getDerivedStateFromProps(nextProps) {
       console.log('I'm never executed)
       this.setState({ status: nextProps.state.status});
    }
GWorking
  • 4,011
  • 10
  • 49
  • 90

2 Answers2

1

As said here

How to update the state of child component from parent?

and going with option 2, what I didn't understand is how to pass a function through props.

If in the child I define there <CHILD message={this.message} then I can call that function with this.props.message in CHILD.

GWorking
  • 4,011
  • 10
  • 49
  • 90
0

We had stumbled upon the same issue. The way we did was, outsource the original state changer to the parent itself. Don't manage states between parent component and child one. If you need to do it, dispatch it using Redux.

For now, the best thing I could say you is:

// Parent Component
class Parent {
  constructor(props) {
    super(props);
    this.state = {};
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
    this.setState({
      SomeVar: "Something"
    });
  }
  render() {
    <Child onUpdate={this.handleClick} />
  }
}

And now with the child, it's easier to send the values this way.

You Nguyen
  • 9,961
  • 4
  • 26
  • 52
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252