iXora Custom Software Development Blog

Read | Practice | Advance

Context – A way to communicate between components in ReactJS

Posted by on in Blog
  • Font size: Larger Smaller
  • Hits: 1810
  • 0 Comments

I am a new chef in React world. Just started learning to prepare some tasty recipe what others like. Suddenly I found myself in a situation where I tried to prepare a menu, but it took lots of hard work to prepare the ingredient. I was looking for a tool and got one that made my day easy.

Enough talk let’s look into it.

What is the recipe?
I have a very tiny application and I would like to pass some data from top level components to some of its child component. Consider the following diagram. For example, I would like to send the logged int user information from App component to User Info component and Side bar component. How will it do that?b2ap3_thumbnail_React-advance-recipe-2019-11-05-16-04-53.pngIn a typical React application, data is passed top-down (parent to child) via props, but this can be cumbersome if you have many components within an application.The way is to pass the data through all the components. Like below:b2ap3_thumbnail_React-advance-recipe-2019-11-05-16-05-56.png
This is not a smart way. We are smart developers.
b2ap3_thumbnail_Picture-1.png
Is there any better approach? Yes, got it. Redux.
b2ap3_thumbnail_Picture-3.png
Uh. But Redux is so complex and need to write lots of boilerplate code. What should I do now?
b2ap3_thumbnail_Picture-4.png 

Here is the tool to reduce the hard work. Context.

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

So, if we use context, we can rewrite the diagram as below: 
b2ap3_thumbnail_React-advance-recipe-2019-11-06-07-45-16.png
Isn’t that cool? Let’s look at the code now. First let’s create a context.

UserContext.js:
Let’s create a context first. The context has a Provider and Consumer.

import React from 'react';

export const {Provider, Consumer} = React.createContext();

App.js:
Let’s use the Provider here to provide some data for the Consumers. It takes one parameter name value which can accept any object. Here we have set the user object. Keep it mind that when the Provider value changes then the Consumers updated automatically.

import React, { Component } from 'react';
import Header from './components/Header';
import { Provider } from './context/UserContext';

class App extends Component {

  state = {
    user: {
      name: 'Ixora'
    }
  }

  handleClick = () => {
    this.setState({
      user: {
        name: 'Ixora Solution'
      }
    })
  }

  render() {
    return (
      <div>
        <h1>App</h1>
        <Provider value={this.state.user.name}>
          <Header ></Header>
        </Provider>
        <button onClick={()=> this.handleClick()}>Click</button>

      </div>

    );
  }
}

export default App;

Header.js

import React, { Component } from 'react';
import TopNavbar from './TopNavbar';

class Header extends Component {
    render() {
        return (
            <div>
                <h1>Header</h1>
                <TopNavbar></TopNavbar>
            </div>

        );
    }
}

export default Header;

TopNavbar.js

import React, { Component } from 'react';
import UserInfo from './UserInfo';

class TopNavbar extends Component {
    render() {
        return (
            <div>
                <h1>TopNavbar</h1>
                <UserInfo></UserInfo>
            </div>

        );
    }
}

export default TopNavbar;

UserInfo.js:

We have consumed the data which were sent by the Provider.

import React, { Component } from 'react';
import { Consumer } from '../context/UserContext';

class UserInfo extends Component {
    render() {        
        return (
            <div>
                <h1>UserInfo</h1>
                <Consumer>
                    {(name) => (
                        <h1>Hello {name}</h1>
                    )}
                </Consumer>

            </div>

        );
    }
}

export default UserInfo;

How do you feel now?
b2ap3_thumbnail_Picture-6.png

But there are some caveats of this recipe. Please read more about it at https://reactjs.org/docs/context.html 

Hope this will help to understand ReactJS “Context”. You can leave comments below for any help or confusion. I will try to address those as soon possible. Also, you can contact iXora Solution ReactJS Team for any assistance on your project implementation at Contact-iXoraReactJS 

Rate this blog entry:
2

Comments

  • No comments made yet. Be the first to submit a comment

Leave your comment

Guest
Guest Wednesday, 21 October 2020