0% found this document useful (0 votes)
13 views7 pages

Context API

context API book

Uploaded by

Mati Chala
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
13 views7 pages

Context API

context API book

Uploaded by

Mati Chala
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
Context API @& 01 Introduction Context API is a solution for a more elegant way of passing data between components by creating global variables, without the need to pass props down the component three manually TO GET STARTED: create a react app: npx create-react-app context-app Add context folder with [Link] inside areal JS [Link] Add components folder with two Yano) Rilo areola lela) JS [Link] JS [Link] oy. What we are building We will be able to access global color variable and change it directly from the components: ComponentA hello world change Easel crenoe 0 blue ComponentB selected color: blue switch jp blue 0s) [Link] Let's create our global state inside the color-context,js file import { createContext, useState } from 'react'; Sige aa eee ame Mogae ad ee selectedColor : null, onColorChange: (newColor) => {}, 2) Coe ee ERM ROLE Gesell ae Ora ee ene const [color, setColor] = useState('red') CORR iC i eaComea eC co 2 iearecoaa 1a Prva een ara onColorChange: handleColorChange, asta eM ieee aed e ee UR thea Sed {children} See Le Tae Lh atie et Led 02) Wrap our App Now in order to use the color content in our application - we need to wrap our App with the ColorProvider ST aaa Ce) ge orf ce Cote el et FU amy 2 rece SU ga eZ import {ColorContextProvider} from './context/color-context'; const root = [Link] ([Link]('root')); rhea (iat EO eaeeyae Cetels o ent irednetaae et ted EN ed Kenge aes a NBL OL taeesae tad ah 05 Component A Let's take a look at an example how we could access and modify global state in [Link] import { useContext } from "react"; import { ColorContext } from "../context/color-context"; const ComponentA = () => { const colorCtx = useContext(ColorContext) ; Tae as elem ele Seem eae cate Ps SMa AC CSAC CLM eae Lee TAG Take} Aled onColorChange( 'green') }> Ce Cm mT Cu) eT colicd onColorChange( 'blue') }> switch to blue Pac yea dk + export default ComponentB;

You might also like