Created
May 5, 2020 10:39
-
-
Save adarsh0d/7a813b0851a33e5a6ccbd68eb73f3002 to your computer and use it in GitHub Desktop.
useReducer
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
import React, {useState, useContext, useReducer} from 'react'; | |
const TextContext = React.createContext() | |
const FontContext = React.createContext() | |
const App = () => { | |
const [state, dispatch] = useReducer((prevState, action) => { | |
switch (action.type) { | |
case 'UPDATE_FONT_FAMILY': | |
return { | |
...prevState, | |
fontFamily: action.payload, | |
}; | |
case 'UPDATE_FONT_SIZE': | |
return { | |
...prevState, | |
fontSize: action.payload, | |
}; | |
case 'UPDATE_TEXT': | |
return { | |
...prevState, | |
text: action.payload, | |
}; | |
}, { | |
fontSize: 14, | |
fontFamily: 'Ariel', | |
text: 'Sample' | |
} | |
const textContext = { | |
text: state.text, | |
updateText: (val) => dispatch({type: "UPDATE_TEXT", payload: val}) | |
} | |
const fontContext = { | |
fontSize: state.fontSize, | |
updateFontSize: (val) => dispatch({type: "UPDATE_FONT_SIZE", payload: val}) | |
fontFamily: state.fontFamily, | |
updateFontFamily: (val) => dispatch({type: "UPDATE_FONT_FAMILY", payload: val}) | |
} | |
return ( | |
<TextContext.Provider value={textContext}> | |
<Child1></Child1> | |
</TextContext.Provider> | |
<FontContext.Provider value={fontContext} | |
<Child2></Child2> | |
<Context.Provider> | |
) | |
} | |
const Child1 = () => { | |
//Need only text | |
const {text, updateText} = useContext(TextContext); | |
return ( | |
<React.Fragment> | |
<input value={text} onChange={(val) => updateText(val)}/> | |
<Child3></Child3> | |
</React.Fragment> | |
) | |
} | |
const Child2 = () => { | |
//This will have font family | |
const {fontFamily, updateFontFamily} = useContext(FontContext); | |
return ( | |
<React.Fragment> | |
<input style=`font-family: ${fontFamily}` onChange={(val) => updateFontFamily(val)}/> | |
<Child3></Child3> | |
</React.Fragment> | |
) | |
} | |
const Child3 = () => { | |
//want to access the fontSize | |
const {fontSize, updateFontSize} = useContext(FontContext); | |
return ( | |
<input value={fontSize} onChange={(e) => updateFontSize(e.target.value)}></input> | |
) | |
} | |
export default App |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment