Jimmy
Jimmy

Reputation: 3860

Getting updated child state into parent state

I am trying to get a parent component to retrieve some information from the child component. Specifically, to have the parent component retrieve the current state of the child. When I try the methodology below, and try to render the updated parent, the updating slows down. Here in the snippet it just returns to me a simple script error. Is there a better way than my current approach to retrieve the child state on componentWillUpdate? Thanks!

class Parent extends React.Component {
   constructor(props) {
    super();
    this.state = {
      parentState: "default",
    }
    this.getChildState = this.getChildState.bind(this);
  }
  
  getChildState(childState) {
    this.setState({
      parentState: childState
    })
  }

  render() {
    return (
      <div>
        <h2>current parentState: {this.state.parentState}</h2>
        <Child getChildState={this.getChildState} />
      </div>
    );
  }
}

class Child extends React.Component {
  constructor() {
    super();
    this.state = {
      onClick: 0,
    }
    this.handleClick = this.handleClick.bind(this);
  }
  
  handleClick() {
    this.setState({
      onClick: this.state.onClick + 1
    })
  }
  
  componentWillUpdate(nextProps, nextState) {
    nextProps.getChildState(nextState.onClick);
  }

 render() {
    return (
      <div>
      <h2>current childState: {this.state.onClick}</h2>
      <button onClick={this.handleClick}>Click Me</button>
      </div>
    );
  }   
}



ReactDOM.render(<Parent />, app);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="app"></div>

Upvotes: 0

Views: 44

Answers (1)

palsrealm
palsrealm

Reputation: 5243

To update the state of the parent, when the state of the child updates, you should use the setState method with the following signature:

setState(updater, [callback])

The handleClick function for the child component should be as follows:

handleClick() {
    this.setState({
      onClick: this.state.onClick + 1
    },()=>this.props.getChildState(this.state.onClick));
  }

This would call the getChildState function when the child state gets updated.

For more information on the setState you can check the React docs

Upvotes: 1

Related Questions