Skip to content

Instantly share code, notes, and snippets.

@KevinVR
Created February 26, 2021 12:09
Show Gist options
  • Save KevinVR/81bf119149aefe0fc9dc8a61c61eded8 to your computer and use it in GitHub Desktop.
Save KevinVR/81bf119149aefe0fc9dc8a61c61eded8 to your computer and use it in GitHub Desktop.
// At the root of our application, create a context
const ThemeContext = React.createContext(themes.light);
// Imagine a themes object would be available with some specific theme values such as colours
function App() {
return (
<ThemeContext.Provider value={themes.dark}>
<MyApp />
</ThemeContext.Provider>
);
}
// Now, our MyApp and any children can use the themes values
// by using the useContext react hook
function MyComponent() {
// Get the current theme by fetching the context with the useContext hook
const theme = useContext(ThemeContext);
// Now we can use the theme values, such as background and colors
return (
<button style={{ background: theme.background, color: theme.foreground }}>
I am styled by theme context!
</button>
);
}
// Example from https://reactjs.org/docs/hooks-reference.html#usecontext
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment