Skip to content

Instantly share code, notes, and snippets.

@zxcfer
Last active May 15, 2020 14:44
Show Gist options
  • Save zxcfer/00d8b505d949875d93d0ac265f74735f to your computer and use it in GitHub Desktop.
Save zxcfer/00d8b505d949875d93d0ac265f74735f to your computer and use it in GitHub Desktop.
React Context
import React from 'react';
import ReactDOM from 'react-dom'
import './App.css'
// creación de contexto
const Context = React.createContext();
// creación de Provider
function AppProvider(props) {
const [contador, setContador] = React.useState(0)
function actualizarContador() {
setContador(contador + 1)
}
const value = [contador, actualizarContador]
return <Context.Provider value={value}>{props.children}</Context.Provider>
}
function ContadorNivel3() {
// recuperamos el estado y la funcion que lo actualiza
const [contador, actualizarContador] = React.useContext(Context)
return (
<div className="borde3">
<p>
<h3>Contador Nivel 3:</h3>
<button onClick={actualizarContador}>Incrementar {contador}</button>
</p>
</div>
)
}
function ContadorNivel2 () {
// recuperamos el estado
const [contador] = React.useContext(Context)
return (
<div className="borde2">
<h3>
Contador Nivel 2: {contador}
</h3>
<ContadorNivel3 />
</div>
)
}
function ContadorNivel1() {
// recuperamos el estado
const [contador] = React.useContext(Context)
return (
<div className="borde1">
<h2>
Contador Nivel 1: {contador}
</h2>
<ContadorNivel2 />
</div>
)
}
function App() {
return (
<div className="App">
<AppProvider>
<ContadorNivel1 />
</AppProvider>
</div>
);
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment