Skip to content

Instantly share code, notes, and snippets.

@adarsh0d
Last active May 5, 2020 10:38
Show Gist options
  • Save adarsh0d/219daff16083ddd09dc984b7c9850ec7 to your computer and use it in GitHub Desktop.
Save adarsh0d/219daff16083ddd09dc984b7c9850ec7 to your computer and use it in GitHub Desktop.
Multi context
import React, {useState, useContext} from 'react';
const TextContext = React.createContext()
const FontContext = React.createContext()
const App = () => {
const [fontSize, updateFontSize] = useState(14);
const [fontFamily, updateFontFamily] = useState('Ariel');
const [text, updateText] = useState('Sample');
const textContext = {
text: text,
updateText: (val) => updateText(val)
}
const fontContext = {
fontSize: fontSize,
updateFontSize: (val) => updateFontSize(val)
fontFamily: fontFamily,
updateFontFamily: (val) => updateFontFamily(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