Skip to content

Instantly share code, notes, and snippets.

@58bits
Created May 26, 2020 17:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 58bits/82bb399f6a955a519ed3429cd9f0d538 to your computer and use it in GitHub Desktop.
Save 58bits/82bb399f6a955a519ed3429cd9f0d538 to your computer and use it in GitHub Desktop.
CustomThemeProvider
// 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