Created
May 29, 2019 11:07
-
-
Save ger86/ca49a0fbc857c00c9e7a7c1dd7a68173 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import React, { createContext, useContext, useReducer } from "react"; | |
import ReactDOM from "react-dom"; | |
const CounterContext = createContext(); | |
const reducer = (state, action) => { | |
switch (action.type) { | |
case "ADD_TO_COUNTER": { | |
return { | |
...state, | |
counter: state.counter + action.value | |
}; | |
} | |
default: | |
return state; | |
} | |
}; | |
const initialState = { | |
counter: 0 | |
}; | |
const CounterContextProvider = props => { | |
const [state, dispatch] = useReducer(reducer, initialState); | |
return ( | |
<CounterContext.Provider value={{ state, dispatch }}> | |
{props.children} | |
</CounterContext.Provider> | |
); | |
}; | |
const Display = () => { | |
const { state } = useContext(CounterContext); | |
return <h1>Valor del contador: {state.counter}</h1>; | |
}; | |
const Increment = () => { | |
const { dispatch } = useContext(CounterContext); | |
return ( | |
<button | |
onClick={() => | |
dispatch({ | |
type: "ADD_TO_COUNTER", | |
value: 1 | |
}) | |
} | |
> | |
Sumar 1 | |
</button> | |
); | |
}; | |
const Decrement = () => { | |
const { dispatch } = useContext(CounterContext); | |
return ( | |
<button | |
onClick={() => | |
dispatch({ | |
type: "ADD_TO_COUNTER", | |
value: -1 | |
}) | |
} | |
> | |
Restar 1 | |
</button> | |
); | |
}; | |
const App = () => { | |
return ( | |
<CounterContextProvider> | |
<Display /> | |
<Increment /> | |
<Decrement /> | |
</CounterContextProvider> | |
); | |
}; | |
ReactDOM.render(<App />, document.getElementById("root")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment