DEV Community

Sina Zinsaz
Sina Zinsaz

Posted on

create dark mode context react mui

To add dark mode to react with context in mui.
Steps to do:

  1. The first step is to install mui in your project:

npm install @mui/material @emotion/react @emotion/styled

Now, let's create a simple dark mode context and toggle between light and dark themes using MUI. Here's an example:

Create a DarkModeContext.js file for the context:

// DarkModeContext.js
import React, { createContext, useContext, useState } from 'react';

const DarkModeContext = createContext();

export const DarkModeProvider = ({ children }) => {
  const [darkMode, setDarkMode] = useState(false);

  const toggleDarkMode = () => {
    setDarkMode((prevMode) => !prevMode);
  };

  return (
    <DarkModeContext.Provider value={{ darkMode, toggleDarkMode }}>
      {children}
    </DarkModeContext.Provider>
  );
};

export const useDarkMode = () => {
  return useContext(DarkModeContext);
};
Enter fullscreen mode Exit fullscreen mode

Wrap your main App component with the DarkModeProvider:

// App.js
import React from 'react';
import { DarkModeProvider } from './DarkModeContext';
import MyApp from './MyApp';

const App = () => {
  return (
    <DarkModeProvider>
      <MyApp />
    </DarkModeProvider>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

Use the useDarkMode hook in your components to access the dark mode state and toggle function:

// MyApp.js
import React from 'react';
import { useDarkMode } from './DarkModeContext';
import { ThemeProvider, createTheme } from '@mui/material/styles';
import { Button, CssBaseline, Paper, Typography } from '@mui/material';

const MyApp = () => {
  const { darkMode, toggleDarkMode } = useDarkMode();

  const theme = createTheme({
    palette: {
      mode: darkMode ? 'dark' : 'light',
    },
  });

  return (
    <ThemeProvider theme={theme}>
      <CssBaseline />
      <Paper style={{ padding: 16, textAlign: 'center' }}>
        <Typography variant="h4" gutterBottom>
          Welcome to My App
        </Typography>
        <Button onClick={toggleDarkMode} variant="contained" color="primary">
          Toggle Dark Mode
        </Button>
      </Paper>
    </ThemeProvider>
  );
};

export default MyApp;
Enter fullscreen mode Exit fullscreen mode

Now, your app is set up with a dark mode context using Material-UI. The DarkModeProvider provides the dark mode state and a function to toggle it, and you can use the useDarkMode hook in your components to access this functionality. The ThemeProvider from MUI allows you to switch between light and dark themes dynamically. The CssBaseline component helps to normalize styles and make the dark mode transition smoother.

Top comments (2)

Collapse
 
soheilkhaledabadi profile image
soheil-khaledabadi

Great

Collapse
 
sinazinsaz profile image
Sina Zinsaz

Thank you