Skip to content

Instantly share code, notes, and snippets.

@adarsh0d
Created May 5, 2020 10:18
Show Gist options
  • Save adarsh0d/896306b16fe7fb2ed4c9cc61a765ff94 to your computer and use it in GitHub Desktop.
Save adarsh0d/896306b16fe7fb2ed4c9cc61a765ff94 to your computer and use it in GitHub Desktop.
useContextMultiple
import React, {useState, useContext} from 'react';
const Context = React.createContext()
const App = () => {
const [fontSize, updateFontSize] = useState(14);
const [fontFamily, updateFontFamily] = useState('Ariel');
const [text, updateText] = useState('Sample');
const providerVal = {
fontSize: fontSize,
updateFontSize: (val) => updateFontSize(val)
fontFamily: fontFamily,
updateFontFamily: (val) => updateFontFamily(val)
text: text,
updateText: updateText
}
return (
<Context.Provider value={providerVal}>
<Child1></Child1>
<Child2></Child2>
<Context.Provider>
)
}
const Child1 = () => {
//Need only text
const {text, updateText} = useContext(Context);
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(Context);
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(Context);
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