Last active
February 22, 2023 10:48
-
-
Save tonicastillo/971f97b22c5a00ec3ef7edd5a5a56124 to your computer and use it in GitHub Desktop.
[REACT Context] #React
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Context.js | |
import React, { createContext, useState, ... } from "react" | |
export const MyContext = createContext() | |
const MyContextProvider = ({children}) => { | |
... | |
//Aquí se manejan u obtienen los datos | |
... | |
return( | |
<MyContext.Provider | |
value={{ | |
variableX: ..., | |
variableY: ..., | |
}} | |
> | |
{children} | |
</MyContext.Provider>) | |
} | |
export default MyContextProvider | |
//--- | |
//App.js | |
import MyContextProvider from "./myContext" | |
... | |
<MyContextProvider> | |
<App /> | |
</MyContextProvider> | |
... | |
//--- | |
//Components.js | |
import React, { useContext } from 'react'; | |
import { MyContext } from "./myContext" | |
// ... | |
function Components() { | |
const context = useContext(MyContext); | |
return <div>The answer is {context.variableX}.</div>; | |
} | |
//-- | |
//Otra forma de obtener los datos | |
<MyContext.Provider> | |
<MyContext.consumer> | |
{context => <ComponenteContain variableX={context.variableX} ... />} | |
... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment