Component Communication using Context..........

Component Communication using Context..........

In this article, we have discussed about using context in React to pass the data from Parent Component to Child Components which are placed at different Nesting Levels. It is often necessary to update the context from a component that is nested somewhere deeply in the component tree. In this article, we will understand how do we Update Context from a Nested Component and how to handle that Update event in the Parent component.

Lets Open Index.js file from our demo-project. I have copied the App Component and Employee Component Code from our Last article, Pasting it here.

class App extends React.Component {
  constructor(props){
    super(props); 
    this.state = {
      data: {Id:101}
    };
  }
  render() {
    return <div>
      <h2>Welcome to App Component</h2>
      <p>
        <label>Employee Id : <b>{this.state.data.Id}</b></label>
      </p>
      <EmployeeContext.Provider value={this.state}>
      <Employee />
        </EmployeeContext.Provider>      
        </div>
  }
}

class Employee extends React.Component {
  static contextType = EmployeeContext;
  render() {
    return <div>
      <h2>Welcome to Employee Component...</h2>
      <p>
        <label>Employee Id : <b>{this.context.data.Id}</b></label>
      </p>
      </div>
  }
}

const element=<App/>
ReactDOM.render(element,document.getElementById('root'));`

Lets create context object, and to this context object lets add one Property with name data and initialize to empty and add New Function named changeEmployeeInfo.

We pass this function down through the context to allow child components to update the context.

const EmployeeContext = React.createContext({
  data: '',
  changeEmployeeInfo: () => {},
});`

Lets create a function named updateEmployeeDetails, change the state object data through the setState Method.

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

Add a New Property to the state object named changeEmployeeInfo whose name is same as the one we have created in our Context Object and Pass this function name as its Value.

this.state = {
      data: {Id:101},
      changeEmployeeInfo:  this. updateEmployeeDetails,
    };

Place a button in the Employee Component and call this context function on Click of the Button.

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

Lets save these changes, navigate to the Browser. We can see that App Component contents and Employee Component contents are being displayed. Lets click on the button and observe that Employee details are changed in both the Components.

We can achieve the same even if the Components are Nested at different Levels.

Thank you for reading .