I'm using MUI with Next.js. My project needs support for both dark and light themes with a custom color palette.
To switch themes, I use useColorScheme
from MUI. Here’s how I set the theme:
const lightPalette = ...
const darkPalette = ...
const getPalette = (mode: 'light' | 'dark' | 'system') => ({
mode,
...(mode === 'light'? lightPalette : darkPalette),
})
And to apply the theme,
import { useColorScheme } from '@mui/material/styles';
...
const [mode, setMode] = useColorScheme()
const theme = createTheme({
colorSchemes: { light: true, dark: true },
...getPalette(mode),
})
...
<ThemeProvider theme={theme} >
...
</ThemeProvider>
The type of mode is 'light', 'dark', or 'system'. When the mode is set to 'system', how do I determine which mode the system is using? Is this the correct way to implement theme switching with Next.js and MUI?
I got an answer from the mui doc and this demo.
We only need a single theme object to set both the dark and light themes. The palettes can be set as follows:
const theme = createTheme({
colorSchemes: {
light: {
palette: { ... }
},
dark: {
palette: { ... }
},
}
})
Note that mode
is not explicitly set in this case. MUI automatically selects the appropriate palette based on current theme mode. Therefore, retrieving the actual mode when mode is set to 'system' was unnecessary. However, if needed, you can get the system mode using:
const { systemMode } = useColorScheme()