التخطي إلى المحتوى الرئيسي

What is React Context?


It works similar to a global variable means if we want to send data from one component to another component directly then we can use React Context.

It solves the limitations of props because props will pass the data from the chain means the first component to second and second to third, we did not send data from first to third directly but using context we can pass data directly.

Example 1st:-

Note:- all components should be defined in same file

import React from "react";
const ThemeContext = React.createContext('light');
export default function ReactContextExample()
{
   return(<ThemeContext.Provider value="Test Context">
        <SecondApp />
   </ThemeContext.Provider>)
}

function SecondApp()
{
   return(<div>
    <ThirdApp />
   </div>)
}

function ThirdApp()
{
   
    return(<ThemeContext.Consumer>
          {value => <h1>{value}</h1>}
    </ThemeContext.Consumer>)
}

Example 2nd:-

Note:- all component should be defined in same file

import { useState, createContext, useContext } from "react";

const UserContext = createContext();

export default function Reactcontextnew() {
  const [user, setUser] = useState("SCS");

  return (
    <UserContext.Provider value={user}>
      <h1>{`Hello ${user}!`}</h1>
      <Component2 />
    </UserContext.Provider>
  );
}

function Component2() {
  return (
    <>
      <h1>Component 2</h1>
      <Component3 />
    </>
  );
}

function Component3() {
  return (
    <>
      <h1>Component 3</h1>
      <Component4 />
    </>
  );
}

function Component4() {
  return (
    <>
      <h1>Component 4</h1>
      <Component5 />
    </>
  );
}

function Component5() {
  const user = useContext(UserContext);

  return (
    <>
      <h1>Component 5</h1>
      <h2>{`Hello ${user} again!`}</h2>
    </>
  );
}

Example Third:-

All Component can be defined in different file.

1)  Create First Component and call second component

import { useState, createContext, useContext } from "react";
import Comsecond from "./Comsecond";
export const UserContext = createContext(); // global variable

export default function Comfirst()
{
    const [user, setUser] = useState("SCS");
    return(<UserContext.Provider value={user}>
       <h1>Welcome {user}</h1>
       <Comsecond />
    </UserContext.Provider>)
}

2)  Create Second Component and Call Third Component

import Comthird from "./Comthird"
export default function Comsecond()
{
    return(<div>
        <h1>Component Second</h1>
        <Comthird />
    </div>)
}

3) Create Third Component and Call Context.

import { useContext,createContext } from "react";
import { UserContext } from "./Comfirst";

export default function Comthird()
{
    const user = useContext(UserContext);
    return(<div>
            <h1>Component Third</h1>
            <h2>{`Hello ${user} again!`}</h2>
          </div>)
}

Another Exanple of Create Context:-

import React from 'react'

const ThemeContext = React.createContext('light'); 
  class App extends React.Component {
  render() {
    // Use a Provider to pass the current theme to the tree below.
    // Any component can read it, no matter how deep it is.
    // In this example, we're passing "dark" as the current value.
    return (
      <ThemeContext.Provider value="RAM">
        <Toolbar />
      </ThemeContext.Provider>
    );
  }
}

// A component in the middle doesn't have to
// pass the theme down explicitly anymore.
function Toolbar() {
  return (
    <div>
      <AButton />
    </div>
  );
}

class AButton extends React.Component {
  // Assign a contextType to read the current theme context.
  // React will find the closest theme Provider above and use its value.
  // In this example, the current theme is "dark".
  static contextType = ThemeContext;
  render() {
    return <button >{this.context}</button>;
  }
}


export default App;

React Context API

The React Context API is a component structure, which allows us to share data across all levels of the application. The main aim of Context API is to solve the problem of prop drilling (also called "Threading"). The Context API in React is given below.

React.createContext

Context.provider

Context.Consumer

Class.contextType

React.createContext

It creates a context object. When React renders a component which subscribes to this context object, then it will read the current context value from the matching provider in the component tree.

Syntax

const MyContext = React.createContext(defaultValue);  

When a component does not have a matching Provider in the component tree, it returns the defaultValue argument. It is very helpful for testing components isolation (separately) without wrapping them.

Context.Provider

Every Context object has a Provider React component which allows consuming components to subscribe to context changes. It acts as a delivery service. When a consumer component asks for something, it finds it in the context and provides it to where it is needed.

Syntax

<MyContext.Provider value={/* some value */}>  

It accepts the value prop and passes to consuming components which are descendants of this Provider. We can connect one Provider with many consumers. Context Providers can be nested to override values deeper within the component tree. All consumers that are descendants of a Provider always re-render whenever the Provider's value prop is changed. The changes are determined by comparing the old and new values using the same algorithm as Object.is algorithm.

Context.Consumer

It is the React component that subscribes to the context changes. It allows us to subscribe to the context within the function component. It requires the function as a component. A consumer is used to request data through the provider and manipulate the central data store when the provider allows it.

Syntax

<MyContext.Consumer>  

       {value => /* render something which is based on the context value */}  

</MyContext.Consumer>  

The function component receives the current context value and then returns a React node. The value argument which passed to the function will be equal to the value prop of the closest Provider for this context in the component tree. If there is no Provider for this context, the value argument will be equal to the defaultValue which was passed to createContext().

Class.contextType

The contextType property on a class used to assign a Context object which is created by React.createContext(). It allows you to consume the closest current value of that Context type using this.context. We can reference this in any of the component life-cycle methods, including the render function.

Note: We can only subscribe to a single context using this API. If we want to use the experimental public class field's syntax, we can use a static class field to initialize the contextType.

React Context API Example

Step1 Create a new React app using the following command.

$ npx create-react-app mycontextapi  

Step2 Install bootstrap CSS framework using the following command.

$ npm install react-bootstrap bootstrap --save    

Step3 Add the following code snippet in the src/APP.js file.

import React, { Component } from 'react';  

import 'bootstrap/dist/css/bootstrap.min.css';  

const BtnColorContext = React.createContext('btn btn-darkyellow');  

class App extends Component {  

  render() {  

    return (  

      <BtnColorContext.Provider value="btn btn-info">  

        <Button />  

      </BtnColorContext.Provider>  

    );  

  }  

}    

function Button(props) {  

  return (  

  <div className="container">  

    <ThemedButton />      

  </div>  

  );  

}  

 class ThemedButton extends Component {    

  static contextType = BtnColorContext;  

  render() {  

    return <button className={this.context} >  

      welcome to javatpoint  

    </button>;  

  }  

}  

export default App;  

In the above code snippet, we have created the context using React.createContext(), which returns the Context object. After that, we have created the wrapper component which returns the Provider component, and then add all the elements as children from which we want to access the context.

تعليقات

المشاركات الشائعة من هذه المدونة

Uncontrolled form input in React-JS

  Uncontrolled form input in React-JS? If we want to take input from users without any separate event handling then we can uncontrolled the data binding technique. The uncontrolled input is similar to the traditional HTML form inputs. The DOM itself handles the form data. Here, the HTML elements maintain their own state that will be updated when the input value changes. To write an uncontrolled component, you need to use a ref to get form values from the DOM. In other words, there is no need to write an event handler for every state update. You can use a ref to access the input field value of the form from the DOM. Example of Uncontrolled Form Input:- import React from "react" ; export class Info extends React . Component {     constructor ( props )     {         super ( props );         this . fun = this . fun . bind ( this ); //event method binding         this . input = React . createRef ();...

JSP Page design using Internal CSS

  JSP is used to design the user interface of an application, CSS is used to provide set of properties. Jsp provide proper page template to create user interface of dynamic web application. We can write CSS using three different ways 1)  inline CSS:-   we will write CSS tag under HTML elements <div style="width:200px; height:100px; background-color:green;"></div> 2)  Internal CSS:-  we will write CSS under <style> block. <style type="text/css"> #abc { width:200px;  height:100px;  background-color:green; } </style> <div id="abc"></div> 3) External CSS:-  we will write CSS to create a separate file and link it into HTML Web pages. create a separate file and named it style.css #abc { width:200px;  height:100px;  background-color:green; } go into Jsp page and link style.css <link href="style.css"  type="text/css" rel="stylesheet"   /> <div id="abc"> </div> Exam...

JDBC using JSP and Servlet

JDBC means Java Database Connectivity ,It is intermediates from Application to database. JDBC has different type of divers and provides to communicate from database server. JDBC contain four different type of approach to communicate with Database Type 1:- JDBC-ODBC Driver Type2:- JDBC Vendor specific Type3 :- JDBC Network Specific Type4:- JDBC Client-Server based Driver  or JAVA thin driver:- Mostly we prefer Type 4 type of Driver to communicate with database server. Step for JDBC:- 1  Create Database using MYSQL ,ORACLE ,MS-SQL or any other database 2   Create Table using database server 3   Create Form according to database table 4  Submit Form and get form data into servlet 5  write JDBC Code:-     5.1)   import package    import java.sql.*     5.2)  Add JDBC Driver according to database ide tools     5.3)  call driver in program         ...