Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

react context

// ---------------- Parent.js 
import {createContext , useState} from "react";

let contextName = createContext( ) // you can optionally pass it a default value // it returns a "provider" object 

let Parent = () => {
    let [count , setCount] = useState()    // returns an [ state variable , state setter fn]. you can pass useState() a default value too
    				// the stateSetter function is async
    return ( 
        <div> 
            <contextName.Provider value={ {count , setCount } } >	// you can send multiple things across to the consumers by adding them in a single object
                <B/>
            </contextName.Provider> 
        </div>
    )
}

export {contextName};
export default Parent;


// file that consumes the context 
// --------- Child.js -----------

import {useContext} from "react";   // import the useContext hook that will allow you to actually use the created and imported context 
import {contextName } from "./Parent";   // import the particular context that you want to use 

let Child = () => {
    let value = useContext(contextName);
    return (
        <div> {value} </div>
    )
}



Comment

react context

//React context allows us to pass data to our component tree without using props.
To use Context, we use the createContext function from React.
The created context includes a Provider and a Consumer property, which are each components.
We wrap the Provider around the component tree that we want to pass
the given value down.
Next, we place the Consumer in the component we want to consume the value.
import { createContext } from 'react';

const NameContext = createContext('');

function App() {
  return (
    <NameContext.Provider value="John Doe">
      <Body />
    <NameContext.Provider>
  );
} 

function Body() {
  return <Greeting />;
} 

function Greeting() {
  return (
    <NameContext.Consumer>
      {name => <h1>Welcome, {name}</h1>}
    //we got function with name argument which we will use
    </NameContext.Consumer>
  );
}

//using useContext hook 
 rewrite our example from earlier, using the useContext hook:

import { createContext, useContext } from 'react';

const NameContext = createContext('');

function App() {
  return (
    <NameContext.Provider value="John Doe">
      <Body />
    <NameContext.Provider>
  );
} 

function Body() {
  return <Greeting />;
} 

function Greeting() {
	const name = useContext(NameContext);
  //useContext with name of context
  return (
    <h1>Welcome, {name}</h1>
  );
}
Comment

Create a context in react

import React, { createContext, useReducer } from "react";
import reducer, { initialState } from "./reducer";

export let todoContext = createContext({});

export default function Provider({ children }) {

  const [state, dispatch] = useReducer(reducer, initialState);

  const values = {
    state,
    dispatch
  };

  return (
    <>
      <todoContext.Provider value={values}>
        {children}
      </todoContext.Provider>
    </>
  );
}
Comment

react create context

import React from "react";
export const ThemeContext = React.createContext();

export default class Theme extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            mode: "dark",
            toggleMode: this.toggleMode
        }
    }
    toggleMode = () => {
        console.log('yes');
        this.setState({
            mode: this.state.mode === 'dark' ? 'light' : 'dark'
        });
    }
    render() {
        return (
            <ThemeContext.Provider value={this.state} >
                {this.props.children}
            </ThemeContext.Provider>
        )
    }
}
Comment

PREVIOUS NEXT
Code Example
Javascript :: elastic get data from specific fields 
Javascript :: getFullYear within moment in angular 
Javascript :: check time javascript 
Javascript :: format javascript date 
Javascript :: javascript split regex new line 
Javascript :: enviar formulario por ajax 
Javascript :: unix to date in javascript 
Javascript :: primitive data types in javascript 
Javascript :: linux cli format json 
Javascript :: else if javascript 
Javascript :: cast object to string javascript 
Javascript :: call json api javascript 
Javascript :: hammer js cdn 
Javascript :: console.log json shopify 
Javascript :: join in mongodb 
Javascript :: npm react dropdown 
Javascript :: filter array of objects with array of objects 
Javascript :: string interpolation in javascript 
Javascript :: jquery fadeout to fadein 
Javascript :: javascript array any 
Javascript :: filter parameters in javascript 
Javascript :: ternary operator javascript 
Javascript :: axios fainally 
Javascript :: install specific version of npm for your project 
Javascript :: react does not send the cookie automatically 
Javascript :: how to insert an item into an array at a specific index in javascript 
Javascript :: website implement jquery in js 
Javascript :: vue custom events 
Javascript :: icon shwoing a box react native vector icons 
Javascript :: access variable from another function javascript 
ADD CONTENT
Topic
Content
Source link
Name
1+1 =