Saturday, July 17, 2021

React - Communication between parent child component

 


import React from 'react';
import ReactDOM from 'react-dom';


class Employee extends React.Component { 
  constructor(props) {
    super(props);

    this.state = {
      updatedSalary : parseInt(this.props.Basic) + 
                      parseInt(this.props.HRA) + 
                      parseInt(this.props.SpecialAllowance)
    }
  }

  getUpdatedSalary = (salary=> {
    this.setState( {updatedSalary : salary });
  }
  render(){
    return <div>
      <h1>Employee Details..</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.state.updatedSalary}</b></label>
      </p>   
      <Salary 
        Basic =  {this.props.Basic} 
        HRA = {this.props.HRA}
        SpecialAllowance = {this.props.SpecialAllowance}
        OnSalaryChanged = {this.getUpdatedSalary}
      ></Salary>               
    </div>
  }

//Employee


class Salary extends React.Component{
  constructor(props){
    super(props);
    this.BasicRef = React.createRef();
    this.HRARef = React.createRef();
    this.SpecialAllowanceRef = React.createRef();
  }
  
  updateSalary = () =>{
    let salary = 
                  parseInt(this.BasicRef.current.value
                  + parseInt(this.HRARef.current.value)
                  + parseInt(this.SpecialAllowanceRef.current.value);
    this.props.OnSalaryChanged(salary);
  }
  
  render(){

    return <div>
      <h1>Salary Details..</h1>
      <p>
      <label>Basic Salary :
        <input type="text"  defaultValue={this.props.Basic}   ref={this.BasicRef}>
        </input></label>
      </p>
      <p>
      <label>HRA : 
        <input type="text" defaultValue={this.props.HRA} ref={this.HRARef}>
      </input></label>
      </p>
      <p>
      <label>Special Allowance : 
        <input type="text" defaultValue={this.props.SpecialAllowance}
         ref={this.SpecialAllowanceRef}></input></label>
      </p>      
      <button onClick={this.updateSalary}>Update</button>
      
    </div>
    }
  }


const elem = <Employee 
              Id="1" Name="ABCD" Location="XYZ" Salary="10000" Basic="1000" 
              HRA="1000" SpecialAllowance="8000"
              ></Employee>



ReactDOM.render(elemdocument.getElementById("root"))              





No comments:

Post a Comment

How to check local and global angular versions

 Use the command ng version (or ng v ) to find the version of Angular CLI in the current folder. Run it outside of the Angular project, to f...