Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update (re-render) the child components in React when the parent's state change?

Okay, I already know one way to do this. However, I am asking this in case I am reinventing the wheel since I am very new to React. I was under the impression that if a parent component passes her state to the child components via props than upon updating the parent's state, the child will re-render if needed. But this does not seem to be the case. I set up this example,

class Child extends Component {
  constructor(props) {
    super(props);
    this.state = {
      number: props.number,
    };
  }

  updateNumber(n) {
    this.setState({number: n});
  }

  render() {
    return (<h1>{this.state.number}</h1>);
  }
}

class Parent extends Component {

  constructor(props) {
    super(props);
    this.state = {
      number: -1,
    };
    this.child = React.createRef();
    setInterval(this.updateState.bind(this), 1000);
  }

  updateState() {
    console.log(this.state);
    this.setState({
      number: Math.floor((Math.random() * 10) + 1),
    });
    // this.child.current.updateNumber(this.state.number);
  }

  render() {
    return (
      <div>
        <Child ref={this.child} number={this.state.number}/>
      </div>
    );
  }
}

In this example, unless I explicitly define a reference and use it to call the child's update function (the commented part), child is not re-rendered each time the parent's state is updated. So is that it? Are you suppose to manually update the state of your children (heh) or should they automatically update (and thus re-render) if their parent's state is passed to them as props.

like image 527
scribe Avatar asked Nov 23 '19 09:11

scribe


1 Answers

One easy option to re-render a child is to update a unique key attribute every time you need a re-render.

<ChildComponent key={this.state.updatedKey}/>

like image 156
Gary Vernon Grubb Avatar answered Oct 02 '22 09:10

Gary Vernon Grubb