Update Child Components from Parent ReactJS

One common challenge in ReactJS is updating Child Components from Parent Component in a form. I faced this scenario recently where after a series of GET calls where the order is decided by the browser threads, data is not always available in the same order.

If you need to set some permissions based on an API GET call and then enable/disable a child component, you can use the following ReactJS lifecycle method:

//Parent Component
shouldComponentUpdate(nextProps, nextState) {
    if (nextState.formReady) {
      return true;
    } else {
      return false;
    }
  }

Set the flag formReady in the series of successive GET calls to true, where you’re sure will be the last call on your Parent form.

//Parent Component GET call inside axios success.
this.setState(
{
  formReady: true,
},() => console.log(this.state.formReady);
);

The shouldComponentUpdate lifecycle method will check for the boolean value and will re-render or refresh the entire form including Child Components.

However, do refer to the documentation before using this method to decide if this suits your needs.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.