Component Communication using Context


In a typical React application, data is passed top-down (parent to child) via props, but this can be difficult for certain types of props (e.g. locale preference, UI theme) that are required by many components which are Nested at different levels within an application. In this article, we will understand how we use Context to pass the data between components at different nesting levels.

Lets take a look at one example. When an Employee is Logged into the React application, we have a Nesting of Components which are making our UI. They are App Component, Employee Component and Salary Component. App Component has an Employee Object and this data is needed by Employee Component and Salary Component in Order to function.

Context provides a way to pass data through the component tree without having to pass props down manually at every level.

Context provides a way to share values between components without having to explicitly pass a prop through every level of the tree.

Context is primarily used when some data needs to be accessible by many components at different nesting levels.

Lets Open index.js file from our demo project, lets create three components. Lets look at this Code. 

class App extends React.Component {
  constructor(props){
    super(props);    
  }  
  render() {
    return <div>
      <h2>Welcome to App Component</h2>  
        </div>
  }
}

class Employee extends React.Component {  
  render() {
    return <div>
      <h2>Welcome to Employee Component...</h2>      
      </div>
  }
}

class Salary extends React.Component {
  render() {
    return <div>
      <h2>Welcome to Salary Component...</h2>     
      </div>
  }
}

Lets Call the Salary Component from Employee Component and Call the Employee Component from App Component. Call the App Component and render it to our DOM.

Lets save these Changes, navigate to the browser and we can see the Output. Now we go to the App Component Class Constructor, create state object, add a new Property called data and assign an Employee Object.

this.state={
      data:{
        Id:101,
        Name:'Pragim Tech'
      }
    };

This Object should be passed from App Component to Employee Component and to Salary Component. We don’t want to Pass the data through Properties from App Component to Employee Component and Pass that data again from Employee Component to Salary Component through Properties.

Lets create context object using React.createContext Method.

const EmployeeContext = React.createContext();

In App Component, We have to store the employee data with in this context object and then access this object in Employee Component and Salary Component from the context.

Every Context object comes with a Provider React component that allows consuming components to subscribe to context changes. Context Provider Accepts a value property to be passed to consuming components that are descendants of this Provider. One Provider can be connected to many consumers. Providers can be nested to override values deeper within the tree. All consumers that are descendants of a Provider will re-render whenever the Provider’s value prop changes. So we modify the way how Employee Component is being Called from App Component 

<EmployeeContext.Provider value={this.state.data}>
      <Employee />
</EmployeeContext.Provider>

Before we go and make changes to Employee and Salary Components to access this Object, lets display the Employee ID in the App Component by reading it from State Object. Now lets go to Employee Component class, lets create a static variable and assign the EmployeeContext Object. 

static contextType = EmployeeContext;

Lets go to render method in the Employee Component, Display the Employee ID by reading it from the context object.

<p>
        <label>Employee Id : <b>{this.context.Id}</b></label>
</p>

Lets repeat the same for Salary Component as well. Lets save these changes, Navigate to the Browser and we can see the Output.

If we make changes to this Employee Data in the App Component, it gets reflected in both Employee Component and Salary Component. To demonstrate this, lets place a button in the App Component, call changeEmpData function onClick of this button. 

<p>
        <button onClick={this. changeEmpData }>Change</button>
</p>

In the changeEmpData function, lets change the Id value and pass it to our setState method.

 changeEmpData=()=>{
    this.setState({data:{Id:102}});
  }

Save these changes, navigate to the browser and lets test this by clicking on the button.

For Video Reference





© 2020 Pragimtech. All Rights Reserved.