Question: ReactJS - Updating parent state when child state is changed

Question

ReactJS - Updating parent state when child state is changed

Answers 1
Added at 2016-12-31 00:12
Tags
Question

I apologize for the lack of working code, but I'm not sure how to go about doing this, so non-working code it is. I am looking to update the this.state.count in the App class when the state of a ToggleBox is altered. I'm sure this has been asked before, thanks in advance.

import React, { Component } from 'react';
import ToggleBox from '../components/ToggleBox';
class App extends Component {
  constructor(props) {
      super(props);
      this.state = {
      total : 60,
      count: 0
    };
  }
  getToggles() {
      let toggles = [];
      for (let i = 0; i < this.state.count; i++) {
        toggles.push(<ToggleBox checked={false} key={i} />);
      }
    return toggles;
  }

  render() {
    let toggles = this.getToggles();
    return (
      <div className="App">
        {{this.state.count}} - {{this.state.total}}
        <div className="container-toggle-box">
            {toggles}
        </div>
      </div>
    );
  }
}

export default App;

...and the component:

import React, {Component} from 'react';
class ToggleBox extends Component {
  constructor(props) {
    super(props);
    this.state = {
      active = this.props.checked
    };
    this.handleClick= this.handleClick.bind(this);
  }
  handleClick() {
    this.setState({active: (this.state.active) ? false : true}
  }
  render() {
    let mark = (this.state.active) ? 'x' : 'o'
      return (
        <span>
          {mark}
        </span>
      );
  }
}

export default ToggleBox;
Answers to

ReactJS - Updating parent state when child state is changed

nr: #1 dodano: 2016-12-31 00:12

You need to pass ToggleBox a function that updates the count.

For example:

toggles.push(<ToggleBox
    checked={false} 
    key={i}
    incrementCount={() => this.setState({count: this.state.count + 1})}
/>);

Then you just call that method in your child component:

handleClick() {
    this.setState({active: (this.state.active) ? false : true};
    this.props.incrementCount();
}

This pattern is often referred to as "Flux" (or, to be more accurate, it's a piece of the overall Flux pattern), and it's a core part of how React was designed to be used. By passing the function in in this way your child component doesn't have to know anything about how count works or how it's incremented. This makes things easy for the child, but more importantly it makes it a lot easier when you want to change how the count works, because there's only a single place (the parent component) which controls it.

Source Show
◀ Wstecz