Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

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>
  );
}
Source by www.freecodecamp.org #
 
PREVIOUS NEXT
Tagged: #react #context
ADD COMMENT
Topic
Name
6+2 =