Interaction between Components in React


The UI of every React application we develop, gets broken down into Components. Every react application we develop will be comprising of multiple components. There will be one Root Component and this component can have one or more Child Components in it. And this nesting can go further as the Application UI gets developed.

Lets take a look at one example. We want to Develop one Employee Component, in which we will be having sections like Employee Personal Info, Project Details, Salary Details Section and Department section.

So the Application UI can be designed in such a way that, we will create components like,

PersonalInfo Component

ProjectDetails Component

SalaryDetails Component

DepartmentComponent

And in EmployeeComponent we will use the above Components.

EmployeeComponent becomes the Parent Component and the rest can be used as Child Components inside EmployeeComponent. It is a very common requirement between these components to share the data. Either from parent to Child, Child to parent or between Siblings. In this article, we will understand how do we pass the data from parent to Child and Child to Parent.

So lets start with the first One, from Parent to Child. There are various ways of making this communication to happen from Parent to Child. The simplest and straight forward way of doing this is through properties.

Lets Open Index.js file, Create Employee Component which will display Employee Details. To save our time, I have kept the Code ready by copying from out last sessions and pasting it here.

class Employee extends React.Component{

  constructor(props){
    super(props);
  }  
  render(){
    return <div>
      <h1>Employee Component...</h1>
    <p>
        <label>Id : <b>{this.props.Id}</b></label>
    </p>
      <p>
        <label>Name : <b>{this.props.Name}</b></label>
    </p>
      <p>
        <label>Location : <b>{this.props.Location}</b></label>
    </p>
      <p>
        <label>Total Salary : <b>{this.props.Salary}</b></label>
    </p>
      </div>
  }
}

Now we want to display the Salary Breakup details.

Lets go ahead and Create Salary Component which will display Employee Salary Information like basic Salary, HRA and Special Allowance. I have kept the Code ready and pasting it here.

class Salary extends React.Component{
  constructor(props){
    super(props);
  }
  render(){
    return <div>
      <h1>Salary Details...</h1>
<p>
        <label>Basic Salary : <b>{this.props.BasicSalary}</b></label>
    </p>
<p>
        <label>HRA : <b>{this.props.HRA}</b></label>
    </p>
    <p>
        <label>Special Allowance : <b>{this.props.SpecialAllowance}</b></label>
    </p>
      </div>
  }
}

Lets Call this Salary Component from Employee Component.

<Salary BasicSalary={this.props.BasicSalary} HRA={this.props.HRA} SpecialAllowance={this.props.SpecialAllowance}></Salary>

Now Employee is the Parent and Salary Component is the Child. Parent Component is passing the Data to Child Components through properties.

Lets Call the Employee Component and lets render it

 const e=<Employee Id="101" Name="Pragim" Location="Bangalore" Salary="50000" BasicSalary="25000" HRA="10000" SpecialAllowance="15000"></Employee>  

  ReactDOM.render(e,document.getElementById("root"));

Lets save these changes , navigate to the browser and we can see the Output. We are passing the data from Employee Component to Salary Component.

Now We want to allow People to change the salary details let it be Basic or HRA or Special Allowance , Resulting Updated Total Salary in the Employee Component should get displayed.

 That means we have to Pass the data from Child to Parent. To allow users to change the salary details, lets create state object in the constructor, add respective properties and initialize them with the data from our props.

constructor(props){
    super(props);
    this.state={
      basic:this.props.BasicSalary,
      hra:this.props.HRA,
      sa:this.props.SpecialAllowance
    };

Lets display the salary details in textboxes by placing input elements and assign the defaultValue by reading from State Object.

<p>
        <label>Basic Salary :<input type="text" defaultValue={this.state.basic} ref="BasicSalary"/></label>
    </p>
<p>
        <label>HRA : <input type="text" defaultValue={this.state.hra} ref="HRA"/></label>
    </p>
    <p>
        <label>Special Allowance : <input type="text" defaultValue={this.state.sa} ref="SpecialAllowance"/></label>
    </p>

Place a Button with the text as Update and Call a function Called as UpdateSalary on the Click.

<button onClick={this.updateSalary}>Update</button>

Implement updateSalary function. In this function we have to calculate TotalSalary based on Basic Salary, HRA and Special Allowance. To access the input values in this function, we can either handle onChange event on every input element and change the state object data accordingly as discussed in our previous session or associate a reference to each input field. 

In this example we add a reference to each input field using ref. So I go and add ref=”basicSalary” ref=”HRA” ref=”SpecialAllowance” to our input fields.

Now lets do the total Salary Calculation in our UpdateSalary function by using refs.referenceName.value.

updateSalary=()=>{
    let salary=parseInt(this.refs.BasicSalary.value)+parseInt(this.refs.HRA.value)+        parseInt(this.refs.SpecialAllowance.value);
  }

This salary should be pushed from Child to Parent and we can do that by using Callbacks.

So after the Salary is Calculated, I push this salary into a new Property called onSalaryChanged and use this property as Callback.

this.props.onSalaryChanged(salary);

Now lets go to the place where this Salary Component is being Called from, add a New Property Called onSalaryChanged and assign a function name assuming getUpdatedSalary from EmployeeComponent which should be Called.

<Salary BasicSalary={this.props.BasicSalary} HRA={this.props.HRA} SpecialAllowance={this.props.SpecialAllowance} onSalaryChanged={this. getUpdatedSalary }></Salary>

Lets implement getUpdatedSalary function in EmployeeComponent. getUpdatedSalary function will receive the salary from Salary Component and we can store this in state object using setState method 

getUpdatedSalary = (salary) => {
this.setState({updatedSalary:salary});
}

and this can be displayed in our Employee Component.

<p>
        <label>Updated Salary : <b>{this.state.updatedSalary}</b></label>
</p>

Lets save these Changes go back to the browser, make some changes to the salary details. Now on Clicking on Update, we can see that Updated Salary gets displayed.

Now we have seen how to pass the data from Parent to Child and child to parent components.

For Video Reference





© 2020 Pragimtech. All Rights Reserved.