Today we’re going to learn how we can add dark mode using React and the MUI design library.
The first thing we’ll do is to create two dark and light themes:
Theme.tsx
// theme.ts import { createTheme, Theme } from '@mui/material/styles'; import '@fontsource/roboto'; import '@fontsource/roboto/100.css'; import '@fontsource/roboto/300.css'; import '@fontsource/roboto/400.css'; const lightTheme: Theme = createTheme({ palette: { mode: 'light', primary: { main: 'teal', }, background: { default: '#FFFFFF' }, }, typography: { fontFamily: 'Roboto, sans-serif', }, components: { MuiDialog: { styleOverrides: { root: { backgroundColor: 'rgba(0, 0, 0, 0.2)', }, }, }, }, }); const darkTheme: Theme = createTheme({ palette: { mode: 'dark', primary: { main: primary, }, background: { default: '#000000', }, }, typography: { fontFamily: 'Roboto, sans-serif', }, components: { MuiDialog: { styleOverrides: { root: { backgroundColor: 'rgba(0, 0, 0, 0.2)', }, }, }, }, }); export { lightTheme, darkTheme };
Once created, let’s generate the logic that will set the dark mode according to the user’s preferences.
Inside our _app.tsx or main file:
const prefersDarkMode = useMediaQuery('(prefers-color-scheme: dark)');
With this mediaQuery, we can set the dark mode if the user has it activated in the system.
We add it inside the rendering function.
const MyApp: React.FC = ({ Component, pageProps }) => { ... const prefersDarkMode = useMediaQuery('(prefers-color-scheme: dark)'); ... return ( <ThemeProvider theme={prefersDarkMode ? darkTheme : lightTheme}>
If we want to change our color file for DarkMode, we will put:
const prefersDarkMode = typeof window !== 'undefined' && window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches; export const marronTransparente = prefersDarkMode ? 'rgba(234, 85, 72, 0.9)' : 'rgba(121, 85, 72, 0.9)';
html
Copy code
Once created, let’s generate the logic that will set the dark mode according to the user’s preferences.
Inside our _app.tsx or main file:
const prefersDarkMode = useMediaQuery('(prefers-color-scheme: dark)');
With this mediaQuery, we can set the dark mode if the user has it activated in the system.
We add it inside the rendering function.
const MyApp: React.FC = ({ Component, pageProps }) => { ... const prefersDarkMode = useMediaQuery('(prefers-color-scheme: dark)'); ... return ( <ThemeProvider theme={prefersDarkMode ? darkTheme : lightTheme}>
If we want to change our color file for DarkMode, we will put:
const prefersDarkMode = typeof window !== 'undefined' && window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches; export const marronTransparente = prefersDarkMode ? 'rgba(234, 85, 72, 0.9)' : 'rgba(121, 85, 72, 0.9)';