~/issues/react-js-how-update-child-component-state-from-parent.md

How to Update Child Component State from Parent Component

2 min readMay 08, 2021by Gorav Singal#reactjs
// TL;DR

Maintain state in the parent component and pass it as props to the child; when parent state changes, React automatically re-renders the child with updated data.

How to Update Child Component State from Parent Component

Problem Statement

I have a parent component which loads some list categories. Based on the selection of this category, I want to show some data in a table. And, I have a table component which displays that data.

So, based on selectio, data on child component must change.

Solution

The solution is to maintain state in parent component, and pass the props to child component. And the child component, will read data from props.

Parent Component Example

import apiClient from '../../components/api/api_client'
import SimpleLayout from '../../components/layout/simple'
import React, { Component } from 'react'
import { Form } from 'react-bootstrap';
import EmailTable from '../../components/emailView/emailTable'

export default class Users extends Component {
  constructor(props) {
    super(props);
    this.state = {
      emails: []
    };
  }

  handleSelection = async (event) => {
    this.setState({
      emails: await apiClient.getEmailsForList(event.target.value)
    });
  }

  render() {
    const emaillist = this.props.emaillist;
    return (
      <SimpleLayout>
        <div className="row">
          <Form>
            <Form.Group controlId="exampleForm.SelectCustomSizeLg">
              <Form.Label>Email Lists</Form.Label>
              <Form.Control as="select" custom
                onChange={this.handleSelection}>
                {emaillist && emaillist.map((each, index) => {
                  return(
                    <option key={index} value={each.name}>{each.name}</option>
                  )
                })}
              </Form.Control>
            </Form.Group>
            <Form.Group>
              <EmailTable emails={this.state.emails} />
            </Form.Group>
          </Form>
        </div>
      </SimpleLayout>
    )
  }
}

Child Component (EmailTable)

Now the child component will just render data from its props.

import React, { Component } from 'react'
import { Table } from 'react-bootstrap';

export default class EmailTable extends Component {
  render() {
    return (
      <Table striped bordered hover variant="dark">
        <thead>
          <tr>
            <th>#</th>
            <th>Name</th>
            <th>Email</th>
            <th>Status</th>
          </tr>
        </thead>
        <tbody>
          {this.props.emails.map((each, index) => {
            return(
              <tr key={index}>
                <td>#</td>
                <td>{each.email}</td>
                <td>{each.email}</td>
                <td>{each.status}</td>
              </tr>
            )
          })}
        </tbody>
      </Table>
  )
}
}

Screenshots

Parent page

Child Component table

Hope it helps.

$ subscribe --weekly

One deep dive a week, in your inbox

System design, AI engineering, trading systems and interview prep. Tested code, real numbers. Free, and you can unsubscribe any time.

or read it on gyanbyte.substack.com

Share

Related Posts

Python SMTP Email Code - Sender Address Rejected - Not Owned By User

Python SMTP Email Code - Sender Address Rejected - Not Owned By User

Introduction In a normal email sending code from python, I’m getting following…

Authenticating Strapi backend with Next.js and next-auth using credentials and jwt

Authenticating Strapi backend with Next.js and next-auth using credentials and jwt

Introduction Strapi is a backend system provides basic crud operations with…

ReactJS - Understanding SetState Asynchronous Behavior and How to correctly use it

ReactJS - Understanding SetState Asynchronous Behavior and How to correctly use it

ReactJS setState is Asynchronous setState() method in ReactJS class components…

ReactJS - How to restrict data type for different kind of data

ReactJS - How to restrict data type for different kind of data

Introduction Javascript is not a strict type language. We can use a variable to…

ReactJS - How to create ReactJS components

ReactJS - How to create ReactJS components

Introduction In this post, we will talk about basic of how to create components…

ReactJS - Basic Form Handling and Form submission

ReactJS - Basic Form Handling and Form submission

Introduction Lets take a look at how forms are being handled in ReactJS. We will…

Latest Posts

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

In the previous article I argued that AI is not killing software engineering…

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

A few months back I approved a PR that was almost entirely AI-generated. It…

How to Debug AI-Generated Code: Understand First, Fix Last

How to Debug AI-Generated Code: Understand First, Fix Last

In the last article I wrote about reviewing AI code before it goes in. This one…

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

Every few weeks somebody sends me a scary headline — “AI will replace all…

The Transactional Outbox Pattern: Never Lose an Event Again

The Transactional Outbox Pattern: Never Lose an Event Again

This is one of those patterns that looks like nothing until you get burnt once…

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Here is a question I like to ask in interviews: your bank account shows a…