Currently, I am developing a Web app built with NEXT JS and MUI 5 latest version alongside using GraphQL.
I am stacked with this point:
I do want to persistent the changing dark mode inside the LocalStorage alongside using this implementation of MUI guidelines by "https://mui.com/customization/dark-mode/#toggling-color-mode".
Is there anyone who can guide me through if I toggle the switch then the Dark or Light mode gonna set in the localStorage? I need all your suggestions.
I am Using with Context API:
import { createContext, useMemo, useState } from 'react'
import { createTheme, ThemeProvider } from '@mui/material/styles'
// TODO: Export this one
export const ColorModeContext = createContext({ toggleColorMode: () => {} })
const ThemeContext = ({ children }) => {
const [mode, setMode] = useState('dark')
const colorMode = useMemo(
() => ({
toggleColorMode: () => {
setMode((prevMode) => (prevMode === 'light' ? 'dark' : 'light'))
},
}),
[]
)
const theme = useMemo(
() =>
createTheme({
palette: {
mode,
primary: {
light: '#757ce8',
main: '#3f50b5',
dark: '#002884',
contrastText: '#fff',
},
secondary: {
light: '#ff7961',
main: '#f44336',
dark: '#ba000d',
contrastText: '#000',
},
},
}),
[mode]
)
return (
<ColorModeContext.Provider value={colorMode}>
<ThemeProvider theme={theme}>{children}</ThemeProvider>
</ColorModeContext.Provider>
)
}
export default ThemeContext
I implemented in my AppBar stuff like this:
// * ___main_appbar_function___
export default function MyAppBar(props) {
const theme = useTheme()
const colorMode = useContext(ColorModeContext)
return (
<NoSsr>
<CssBaseline />
<HideOnScroll {...props}>
<AppBar color='inherit'>
<Toolbar variant='dense' component='div'>
<Box sx={root}>
<MySideBar />
<Typography component='div' variant='h5' textAlign='center'>
PJK
</Typography>
<Box sx={right}>
{/* <AuthModal /> */}
<motion.div
whileTap={{ rotate: 360 }}
// whileHover={{ rotate: 360 }}
transition={{ type: 'spring', stiffness: 50 }}
>
<IconButton onClick={refreshPage}>
<RotateRightIcon />
</IconButton>
</motion.div>
<IconButton
sx={{ ml: 1 }}
onClick={colorMode.toggleColorMode}
color='inherit'
>
{theme.palette.mode === 'dark' ? (
<Brightness7Icon />
) : (
<Brightness4Icon />
)}
</IconButton>
</Box>
</Box>
</Toolbar>
</AppBar>
</HideOnScroll>
<Toolbar />
</NoSsr>
)
}
