Skip to content

Instantly share code, notes, and snippets.

@tonicastillo
Last active February 22, 2023 10:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tonicastillo/971f97b22c5a00ec3ef7edd5a5a56124 to your computer and use it in GitHub Desktop.
Save tonicastillo/971f97b22c5a00ec3ef7edd5a5a56124 to your computer and use it in GitHub Desktop.
[REACT Context] #React
//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