Updating Parent Component State From Children Components In React With TypeScript (TSX Project)

Many people wonder how to update the state of a parent component from its child component since we can only pass props down from the parent to the child in React, as data flow is unidirectional in React applications. Well, through this blog, I will try to clear up the confusion.

Have you ever wondered if we can only pass props down from the parent to the child in React? As data flow is unidirectional in React applications, then how would it be possible to update the state of the parent component from its child component?

Let’s take an example to understand the situation. I have developed a sample application which meets the above requirement. The example uses React with TypeScript.

In the example below, we have three components - “ParentLevel”, “ChildLevel1” and “ChildLevel2” - having a relationship of parent and child and grandchild components.

  1. import React, { Component } from 'react';  
  2.   
  3. interface IEmployee {  
  4.     id: number;  
  5.     name: string;  
  6.     username: string;  
  7.     email: string;  
  8.     isExpand: boolean;  
  9. }  
  10. interface IGroupWithEmploye {  
  11.     departmentName: string;  
  12.     employees: IEmployee[];  
  13. }  
  14.   
  15. interface IStateForParentLevel {  
  16.     GroupWithEmployes: IGroupWithEmploye[];  
  17. }  
  18.   
  19. export default class ParentLevel extends Component<{}, IStateForParentLevel>{  
  20.     public constructor(props: any, state: IStateForParentLevel) {  
  21.         super(props);  
  22.         this.state = {  
  23.             GroupWithEmployes: [] as IGroupWithEmploye[]  
  24.         }  
  25.     }  
  26.     componentDidMount() {  
  27.         var FileData = require('../../sampledata/EmployeeData.json');  
  28.         FileData.map(function (object: any, i: any) {  
  29.             object.employees.map(function (employee: any, j: any) {  
  30.                 employee.isExpand = false;  
  31.                 return employee;  
  32.             })  
  33.             return object;  
  34.         })  
  35.         this.setState({ GroupWithEmployes: FileData });  
  36.   
  37.         var manageColumnSortingOrder = [{  
  38.             key: "id",  
  39.             Name: "ID",  
  40.             sortingOrder: "ASC",  
  41.             filterContent: ""  
  42.         },  
  43.         {  
  44.             key: "name",  
  45.             Name: "Name",  
  46.             sortingOrder: "ASC",  
  47.             filterContent: ""  
  48.         },  
  49.         {  
  50.             key: "username",  
  51.             Name: "User Name",  
  52.             sortingOrder: "ASC",  
  53.             filterContent: ""  
  54.         },  
  55.         {  
  56.             key: "email",  
  57.             Name: "Email",  
  58.             sortingOrder: "ASC",  
  59.             filterContent: ""  
  60.         }];
  61.         
  62.     }  

  63.     onCollapseExpandColumn(empId:number){  
  64.         console.log("call onCollapseExpandColumn");  
  65.         var initialRows = this.state.GroupWithEmployes;  
  66.   
  67.         console.log(this.state);  
  68.         initialRows.map(function (department: any, i: any) {  
  69.             department.employees.map(function (emp: any, j: any) {  
  70.                 if (emp.id == empId) {  
  71.                     emp.isExpand = !emp.isExpand;  
  72.                 }  
  73.   
  74.                 return emp;  
  75.             })  
  76.             return department;  
  77.         })  
  78.         this.setState({ GroupWithEmployes: initialRows });  
  79.     }  
  80.     render() {  
  81.         console.log(this.state.GroupWithEmployes);  
  82.         var ParentLevelThis=this;  
  83.         return (  
  84.             <table className="table table-striped" style={{ marginTop: 20 }}>  
  85.                 <thead>  
  86.                     <tr>  
  87.                         <th>  
  88.                                
  89.                         </th>  
  90.                         <th>  
  91.                             ID  
  92.                         </th>  
  93.                         <th>  
  94.                             Name  
  95.                         </th>  
  96.                         <th>  
  97.                             User Name  
  98.                         </th>  
  99.                         <th>  
  100.                             Email ID  
  101.                         </th>  
  102.                     </tr>  
  103.   
  104.                 </thead>  
  105.                 <tbody>  
  106.                     {  
  107.                         this.state.GroupWithEmployes.map(function (group, index) {  
  108.                             return <ChildLevel1 onClickCallParentLevelMethod={ParentLevelThis.onCollapseExpandColumn.bind(ParentLevelThis)} department={group} key={index} ></ChildLevel1>  
  109.                         })  
  110.                     }  
  111.                 </tbody>  
  112.             </table>  
  113.   
  114.         )  
  115.     }  
  116.   
  117. }  
  118.   
  119. interface IChildLevel1 {  
  120.     department: IGroupWithEmploye;  
  121.     onClickCallParentLevelMethod:(empId:number)=>void;  
  122. }  
  123. class ChildLevel1 extends Component<IChildLevel1, {}>{  
  124.   
  125.     onCollapseExpandColumn(empId:number){  
  126.         console.log("call ChildLevel1 onCollapseExpandColumn");  
  127.         this.props.onClickCallParentLevelMethod(empId);  
  128.      }  
  129.   
  130.     render() {  
  131.         var ChildLevel1This=this;  
  132.         return (  
  133.   
  134.             <React.Fragment>  
  135.                 <tr>  
  136.                     <td colSpan={5}>  
  137.                         Department : {this.props.department.departmentName}  
  138.                     </td>  
  139.                 </tr>  
  140.                 {  
  141.                     this.props.department.employees.map(function (employee, index) {  
  142.                         return <ChildLevel2 onClickCallChildLevel1Method={ChildLevel1This.onCollapseExpandColumn.bind(ChildLevel1This)} employee={employee} key={index} ></ChildLevel2>  
  143.                     })  
  144.                 }  
  145.   
  146.             </React.Fragment>  
  147.         )  
  148.     }  
  149. }  
  150.   
  151. interface IChildLevel2 {  
  152.     employee: IEmployee;  
  153.     onClickCallChildLevel1Method:(userId:number) => void;  
  154. }  
  155. class ChildLevel2 extends Component<IChildLevel2, {}>{  
  156.   
  157.     onCollapseExpandColumn(empId:number){  
  158.         this.props.onClickCallChildLevel1Method(empId);  
  159.      }  
  160.     render() {  
  161.         return (  
  162.             <React.Fragment>  
  163.             <tr>  
  164.                 <td><a className="collapseExpand" onClick={()=>this.onCollapseExpandColumn(this.props.employee.id)} >  
  165.                         <i className={(this.props.employee.isExpand ? "fas fa-caret-down" : "fas fa-caret-right")}></i>  
  166.                         </a></td>  
  167.                 <td>{this.props.employee.id}</td>  
  168.                 <td>{this.props.employee.name}</td>  
  169.                 <td>{this.props.employee.username}</td>  
  170.                 <td>{this.props.employee.email}</td>  
  171.             </tr>  
  172.             {  
  173.                 (this.props.employee.isExpand) && (  
  174.                  <tr>  
  175.                       <td> </td>  
  176.                      <td colSpan={4}>  
  177.                     <table>  
  178.                         <tbody>  
  179.                         <tr>  
  180.                             <td>ID</td>  
  181.                             <td> {this.props.employee.id}</td>  
  182.                         </tr>  
  183.                         <tr>  
  184.                             <td>Name</td>  
  185.                             <td> {this.props.employee.name}</td>  
  186.                         </tr>  
  187.                         <tr>  
  188.                             <td>User Name</td>  
  189.                             <td> {this.props.employee.username}</td>  
  190.                         </tr>  
  191.                         <tr>  
  192.                             <td>Email</td>  
  193.                             <td> {this.props.employee.email}</td>  
  194.                         </tr>  
  195.                         </tbody>  
  196.                     </table>  
  197.                     </td>  
  198.                 </tr>)  
  199.             }  
  200.             </React.Fragment>  
  201.         )  
  202.     }  
  203. }  

We render “ChildLevel1” component from the “ParentLevel” component and “ChildLevel2” component from the “ChildLevel1” component.

As per our requirement, we want to update the “ParentLevel” component’s state onClick of the Expand/Collapse button icon which is rendered in “ChildLevel2” component.

  • In “ChildLevel2” Component, we have called “onCollapseExpandColumn” method of the same component on click of Expand/collapse icon.

  • In “ChildLevel2” Component on “onCollapseExpandColumn” method, we have triggered “ChildLevel1” component’s method using props(this.props(“this.props.onClickCallChildLevel1Method” ))

  • In “ChildLevel1”, we have bound “onCollapseExpandColumn” method so it gets triggered from “ChildLevel2” component’s method.

  • Same as on “onCollapseExpandColumn” method’s call in “ChildLevel1”, we have called “ParentLevel” component’s method using 

    this.props (this.props.onClickCallParentLevelMethod(empId); )
  • In “ParentLevel” component, we have bound “onCollapseExpandColumn” method so it is triggered from “ChildLevel1” component’s method.

  • In “onCollapseExpandColumn” method of “ParentLevel” component, we have updated the state.
Updating Parent Component State From Children Components In React With TypeScript (TSX Project)