Created
May 26, 2020 17:22
-
-
Save 58bits/82bb399f6a955a519ed3429cd9f0d538 to your computer and use it in GitHub Desktop.
CustomThemeProvider
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
// https://techinscribed.com/building-react-app-using-material-ui-with-support-for-multiple-switchable-themes/ | |
import React, { useState } from 'react' | |
import { ThemeProvider } from '@material-ui/core/styles' | |
import getTheme from './base' | |
// eslint-disable-next-line no-unused-vars | |
export const CustomThemeContext = React.createContext( | |
{ | |
currentTheme: 'normal', | |
setTheme: null, | |
}, | |
) | |
const CustomThemeProvider = (props) => { | |
// eslint-disable-next-line react/prop-types | |
const { children } = props | |
// Read current theme from localStorage or maybe from an api | |
const currentTheme = localStorage.getItem('appTheme') || 'normal' | |
// State to hold the selected theme name | |
const [themeName, _setThemeName] = useState(currentTheme) | |
// Retrieve the theme object by theme name | |
const theme = getTheme(themeName) | |
// Wrap _setThemeName to store new theme names in localStorage | |
const setThemeName = (name) => { | |
localStorage.setItem('appTheme', name) | |
_setThemeName(name) | |
} | |
const contextValue = { | |
currentTheme: themeName, | |
setTheme: setThemeName, | |
} | |
return ( | |
<CustomThemeContext.Provider value={contextValue}> | |
<ThemeProvider theme={theme}>{children}</ThemeProvider> | |
</CustomThemeContext.Provider> | |
) | |
} | |
export default CustomThemeProvider |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment