useContext Part-2


In this article, we will continue our discussion about useContext hook in React.

In the last article, we have discussed about how do we use Context in React to Pass the Employee data from App Component to its descendants.

Resulting we were able to access the Employee Data in both Employee Component and Salary Component. 

Now what if if we want to update the Employee Salary in the Salary Component or what if if we want to update the Employee Data from any of the Child Components.  

Lets see how do we do that. 

Lets display the Employee salary value in App Component as well as in Employee Component so that we can visualize the Salary Change Value in all the Components. 

Now in App Component we have one function called as setEmployee using which we can update the employee data. 

We can pass even this function to the Child Components along with the employee data using the value attribute. 

Lets create one object which will hold both employee data and the setEmployees function.

<employeeContext.Provider value={{data:employee, updateFunction:setEmployee}}>
          <Employee></Employee>
 </employeeContext.Provider> 

Now in Employee Component, we get the Employee details using context.data property as that is the Property through which we have passed the data. Lets make the changes accordingly. 

We will do the same changes even in Salary Component. 

Now lets place a button in the Salary Component using which we will update the Employee Salary. Lets call a function on Click of this button. 

Now we will implement the updateSalary function. With in this updateSalary function, we will call our update function and to that function we will pass the employee object and the updated Salary. 

Save the changes. Navigate to the browser. We can see that Salary is being displayed in all the three components. 

Now click on Update button, we can see that the Salary gets updated in all the three Components. 

Lets add two more components to our code. One Component contents will be displayed if the Employee is Permanent and we will show the other component contents if the Employee is Contract. 

I have the code handy for these components and I am pasting it here. 

Now in the Employee Component, we have to display one of this Component based on the Employment Type. 

Lets add one new Property to our employee object in the App Component called as Type and we will initialize it to Contract. 

If that is the case our Employee Component should render Contract Component and whenever we change the Type to Permanent Employee Component should render Permanent Component Contents. 

To accomplish this we use context.consumer

It is A React component that subscribes to context changes. This Component Requires a function as a child. The function receives the current context value and returns a React node. 

If the employee Type is Permanent we Call Permanent Component else we call the other Component. 

Now lets place a button in Employee Component using which we can change the Employment type. We will handle onClick event. 

With in the function, lets change the Type. 

Save the Changes, navigate to the browser. 

We can see that by default we get the Contents of Contract Component. Change the Employment type by clicking on the button. We can see that we get the Contents of Permanent Component. 

With this I hope we are very clear on how to use useContext hook in React. 

import ReactDOM from "react-dom";
import React, { Component, useState, useContext } from "react";

const employeeContext=React.createContext();

function App(){

  const [employee,setEmployee]=useState({Id:101,Name:'Pragim',Type:'Contract',
                                Location:'Bangalore',Salary:12345, EmploymentType:'Contract'});
  return(
    <div>
      <h2>Welcome to App Component...</h2>
      <p>
        <label>Employee Salary : <b>{employee.Salary}</b></label>
      </p>
      <employeeContext.Provider value={{data:employee,updateEmployee:setEmployee}}>
          <Employee></Employee>
      </employeeContext.Provider>           
    </div>
  );
}

function Employee(){
  let context=useContext(employeeContext);

  function changeEmploymentType(){
    context.updateEmployee({...context.data,EmploymentType:'Permanent'});
  }
  return(
    <div>
      <h2>Welcome to Employee Component...</h2>
      <p>
        <label>Employee ID : <b>{context.data.Id}</b></label>
      </p>
      <p>
        <label>Employee Name : <b>{context.data.Name}</b></label>
      </p>  
      <p>
        <label>Employee Salary : <b>{context.data.Salary}</b></label>
      </p>    
      <employeeContext.Consumer>
        {value=>value.data.EmploymentType==='Permanent'?
              <Permanent></Permanent>:<Contract></Contract>}
      </employeeContext.Consumer>
      <button onClick={changeEmploymentType}>Make Permanent</button>
      <Salary></Salary>
    </div>
  );
}
function Salary(){
  let context=useContext(employeeContext);

  function updateSalary(){
    context.updateEmployee({...context.data,Salary:15000});
  }
  return(
    <div>
      <h2>Welcome to Salary Component...</h2>
      <p>
        <label>Employee ID : <b>{context.data.Id}</b></label>
      </p>
      <p>
        <label>Employee Salary : <b>{context.data.Salary}</b></label>
      </p>
      <button onClick={updateSalary}>Update</button>
    </div>
  );
}

function Permanent(){
  return (
    <div>
      <h2>Permanent Component Contents...</h2>
    </div>
  );
}

function Contract(){
  return(
    <div>
      <h2>Contract Component Contents...</h2>
    </div>
  )
}
const element=<App></App>

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

Video Reference:





© 2020 Pragimtech. All Rights Reserved.