vrotos
vrotos

Reputation: 33

Children component's props are not updated when the parent component start as null

// 1 - Parent - Wrong
render() {
const { record } = this.state;
if (!record) { return null; }
return (
  <div>
    <p>Now this is visible</p>
    <Children id={record.id};
  </div>
  );
}

// 2 - Parent - Right
render() {
  const { record } = this.state;
  const recordId = record ? record.id : null;

  return (
    <div>
      <p>Now this is visible</p>
      <Children id={recordId};
    </div>
  );
}

// Children
componentWillReceiveProps(nextProps) {
  console.log(nextProps.id);
}

If the state becomes: this.state = { record: { id: 'demo' } }

Writing the code the first approach, nextProps is always undefined in the Children's componentWillReceiveProps even if the Parent record becomes visible because it received a new state.

While the second works as it should.

Why does the first work incorrectly?

Upvotes: 0

Views: 81

Answers (1)

Abraham Gnanasingh
Abraham Gnanasingh

Reputation: 897

As per the official document, React doesn't call componentWillReceiveProps with initial props during mounting. It only calls this method if some of component's props may update.

I had a workaround for your problems and created the following fiddle for the solution. It should solve all your problems.

Fiddle - https://jsfiddle.net/4o7o6cmw/4/

Upvotes: 1

Related Questions