ReactJS - static contextType Property



The Context API in React helps us to quickly handle and share state across our application. So we will see how to use static contextType in React class components to read and use context data.

Context in React is an approach for sending data across components without having to pass props down through every level of the component tree. This is very helpful for sharing data like themes, user authentication, or any global information that different components require access to.

Syntax

const MyContext = React.createContext();

First, we need to create a context using React.createContext(). This will be the context that we want to access in our component.

How to use it?

To use the Context API, we can follow the below steps −

  • First we need to create context. And we can use the createContext function to create a context.

  • Next we will wrap the component tree with a Context Provider to provide context to the components that need it.

  • To access the context's value in function components we will use the useContext hook. And to access the context in class components we can use the static contextType attribute.

Examples

Example

In this app we will display whether the user is authenticated or not. So we will have an App Component which will Manage the state of user authentication (true or false). And it will provide the authentication state to its child components using the AuthContext.Provider. And then we will create an AuthStatus Component which will use static contextType to access the authentication context. And we will display a message as per the user is logged in or not.

import React, { createContext, Component } from 'react';

const AuthContext = createContext();
class App extends Component {
   state = {
      isAuthenticated: true,
   };   
   render() {
      return (
         <AuthContext.Provider value={this.state.isAuthenticated}>
         <AuthStatus />
         </AuthContext.Provider>
      );
   }
}
class AuthStatus extends Component {
   static contextType = AuthContext;   
   render() {
      const isAuthenticated = this.context;   
      return (
         <div>
            <h1>User Authentication App</h1>
            {isAuthenticated ? <p>User is logged in</p> : <p>User is not logged in</p>}
         </div>
      );
   }
}

export default App;

Output

user authentication app

So we can see that the user is logged in as we have set isAuthenticated state to true. If we set it to false then it will show the message that “User is not logged in”.

Example − Language Selection App

In this app we will have a functionality to allow user to select their preferred language. So we will have an App Component. This component will manage the state of the selected language. And also provide the language state to its child components using the LanguageContext.Provider. And then we will have one more component called LanguageSelector, and this component will use static contextType to access the language context. And it will render a simple UI that shows the selected language.

import React, { createContext, Component } from 'react';

const LanguageContext = createContext();
class App extends Component {
   state = {
      language: 'English',
   };   
   render() {
      return (
         <LanguageContext.Provider value={this.state.language}>
            <LanguageSelector />
         </LanguageContext.Provider>
      );
   }
}

class LanguageSelector extends Component {
   static contextType = LanguageContext;   
   render() {
      const language = this.context;   
      return (
         <div>
            <h1>Language Selection App</h1>
            <p>Selected Language: {language}</p>
         </div>
      );
   }
}

export default App;

Output

language selection app

So we can see the output as shown above in which the selected language is English. So we can change the language as per user requirement.

Example − Class Components with static contextType

The static contextType property can be used to get context in a class component. We can create a simple example with a button, so with the help of it we can switch between light and dark themes which allow us to change the theme dynamically.

import React, { Component } from 'react';

// Create a context
const ThemeContext = React.createContext();
class App extends Component {
   constructor(props) {
      super(props);
      this.state = {
         theme: 'light', // Initial theme is light
      };
   }   
   toggleTheme = () => {
      // Update the context value 
      this.setState((prevState) => ({
         theme: prevState.theme === 'light' ? 'dark' : 'light',
      }));
   };   
   render() {
      return (
         <ThemeContext.Provider value={this.state.theme}>
         <div>
            <Button onClick={this.toggleTheme}>Toggle Theme</Button>
         </div>
         </ThemeContext.Provider>
      );
   }
}
class Button extends Component {
   
   // Specify the context
   static contextType = ThemeContext;
   
   render() {
      // Access the context value
      const theme = this.context;
      const className = 'button-' + theme;
   
      return (
         <button className={className} onClick={this.props.onClick}>
            {this.props.children}
         </button>
      );
   }
}

export default App;

When we click the "Toggle Theme" button, the theme will dynamically change between light and dark colors, and the style of the button will change accordingly.

Summary

The static contextType property is an easy way to use context in React class components, because it provides a simple approach to get context information. We can reduce our code by declaring the context if our component requires. Using static contextType we can make it easier to maintain global state and exchange data across our application.

reactjs_reference_api.htm
Advertisements