Last active
July 22, 2019 18:19
-
-
Save chathuranga94/52b27d8d3beba12d49d8ee45c2b33768 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, { useContext, useReducer } from 'react'; | |
const AppContext = React.createContext({}); | |
const App = () => { | |
let initialState = { lang: 'en', color: 'blue'}; | |
let reducer = (state, action) => { | |
switch (action.type) { | |
case "change-language": | |
return { ...state, lang: action.payload };; | |
} | |
}; | |
let [state, dispatch] = useReducer(reducer, initialState); | |
let value = { state, dispatch }; | |
return ( | |
<AppContext.Provider value={value}> | |
<LanguagePicker /> | |
<Menu /> | |
</AppContext.Provider> | |
); | |
} | |
const Menu = () => <MenuItem />; | |
const LanguagePicker = () => { | |
const { state, dispatch } = useContext(AppContext); | |
let setLanguage = lang => () => dispatch({ type: "change-language", payload: lang }); | |
return ( | |
<div> | |
<button onClick={setLanguage('en')}>English</button> | |
<button onClick={setLanguage('fr')}>French</button> | |
</div> | |
); | |
} | |
const MenuItem = () => { | |
const { state, dispatch } = useContext(AppContext); | |
return ( | |
<div> | |
<p>Theme colour: {state.color}</p> | |
<p>Locale: {state.lang}</p> | |
</div> | |
); | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment