Friday, April 13, 2018

Context in React 16.3

Context in React in a feature which helps us pass data through the component tree without having to pass them as props through each level of sub-component. Without context the only way to pass a set of values through a component tree is to pass them as props to each level of child component.

This might get complex when we want to share a few global values to many of the sub-components in the component tree. For example data like language preference or style preference which should be re-used by most of the components should be easier to share across various components.

React 16.3 Context helps us solve this using the new Context API React.createContext(). Calling the createContext() provides us a Provider and a Consumer component. The Provider declares the data which should be made available to the child components in the component tree. The Consumer components can receive the data declared in the Provider.

const ThemeContext = React.createContext({color: 'blue'});

class ParentComponent extends React.Component {
  render() {
    return (
      <ThemeContext.Provider value={{color: 'green'})>
        <ChildComponent1 />
        <ChildComponent2 />
        <ChildComponent3 />
      </ThemeContext.Provider>
    );
  }
}

function ChildComponent1() {
    <ThemeContext.Consumer>
        {(context) => {
          return (
            <div style={{background: context.color}}/>
          );
        }}     
    </ThemeContext.Consumer>
};

Search Flipkart Products:
Flipkart.com

No comments: