DEV Community

Just another React Dev
Just another React Dev

Posted on • Updated on

Add MUI v5 Theme Switcher in NextJs/React

Hello guys today i will show you how to add MUI Theme Switcher in your React App.

Prerequisite of this tutorial is to have intermediate knowledge of React and MUI (formally known as material-UI)

Lets Initiate the App and install required dependencies first

  1. run following command to initiate the project
npx create-react-app app-name
Enter fullscreen mode Exit fullscreen mode
  1. Install MUI-v5 UI library and supporting dependencies
npm install @mui/material @emotion/react @emotion/styled js-cookie
Enter fullscreen mode Exit fullscreen mode
  1. Lets run the app by hitting the following command
npm start 
Enter fullscreen mode Exit fullscreen mode
  1. lets do some coding in editor of your choice navigate to folder to structure in ./src folder create a folder with name Components as shown in below

Project root Directory with Component Folder

  1. In Components create component with the name of AppBar with including File AppBar.js
  2. I am using dummy code straight from MUI-v5 website you can add your own Code
  3. after copying/writing your code lets add select dropdown to for theme options

AppbarJs file with Select Dropdown

  1. create Themes folder in ./src folder to store our themes theme.js will be our default theme with default value

Theme director with themejs file

  1. in theme.js file lets initiate theme configuration for our default this will apply to all other theme options so our theme.js should look like this

Image description

  1. time to do some heavy lifting go to App.js add following code
import Appbar from "./Components/Appbar/Appbar";
import React, { useState } from "react";
import brownTheme from "./Themes/BrownTheme";
import darkBlue from "./Themes/darkBlue";
import darkgreen from "./Themes/darkgreen";
import someBlue from "./Themes/SomethingBlue";
import theme from "./Themes/theme";
import Cookies from "js-cookie";
import { ThemeProvider } from "@mui/material";
import DummyContent from "./Components/DummyContent/dummyContent";
const themeArray = [
  {
    name: "Default",
    themeName: theme,
  },

  {
    name: "Dark Blue",
    themeName: darkBlue,
  },
  {
    name: "Brown Theme",
    themeName: brownTheme,
  },
  {
    name: "Green Theme",
    themeName: darkgreen,
  },

  {
    name: "Some Blue",
    themeName: someBlue,
  },
];
function App() {
  const [selectedThemeName, setSelectedThemeName] = useState(
    Cookies.get("selectedThemeName") || "Default"
  );
  const [selectedTheme, setSelectedTheme] = useState(
    themeArray.find((theme) => theme.name === selectedThemeName).themeName
  );
  const handleChange = (event) => {
    const newThemeName = event.target.value;
    setSelectedThemeName(newThemeName);
    setSelectedTheme(
      themeArray.find((theme) => theme.name === newThemeName).themeName
    );
    Cookies.set("selectedThemeName", newThemeName, {
      expires: 365,
      sameSite: "None",
      secure: true,
    });
  };
  return (
    <React.Fragment>
      <ThemeProvider theme={selectedTheme}>
        <Appbar
          setSelectedTheme={setSelectedTheme}
          handleChange={handleChange}
          selectedTheme={selectedTheme}
          selectedThemeName={selectedThemeName}
          themeArray={themeArray}
        />
        <DummyContent />
      </ThemeProvider>
    </React.Fragment>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode
  1. after adding above code your App.js your file should look like this

Image description

Image description

Image description

12.Add Additional theme files from github link at the end of the post or you can create your own themes with colors and customization of your own .

  1. your Themes folder should look like

Image description

14.lets move to Navbar.js to make theme switcher.Add following code

import React from "react";
import AppBar from "@mui/material/AppBar";
import Box from "@mui/material/Box";
import Toolbar from "@mui/material/Toolbar";
import Typography from "@mui/material/Typography";
import { Select, MenuItem } from "@mui/material";
const Appbar = ({ handleChange, selectedThemeName, themeArray }) => {
  return (
    <React.Fragment>
      <Box sx={{ flexGrow: 1 }}>
        <AppBar position="static">
          <Toolbar>
            <Typography variant="h6" component="div" sx={{ flexGrow: 1 }}>
              News
            </Typography>
            <Box
              sx={{
                width: "200px",
              }}
            >
              <Select
                sx={{
                  backgroundColor: "primary.main",
                  color: "common.white",
                  maxWidth: "100%",
                }}
                autoWidth
                value={selectedThemeName}
                onChange={handleChange}
              >
                {themeArray.map((theme) => (
                  <MenuItem key={theme.name} value={theme.name}>
                    {theme.name}
                  </MenuItem>
                ))}
              </Select>
            </Box>
          </Toolbar>
        </AppBar>
      </Box>
    </React.Fragment>
  );
};

export default Appbar;

Enter fullscreen mode Exit fullscreen mode

15.Navbar.js should look like this

Image description

Image description

16.almost done with switcher lets add some gibbrish UI code to check if its working or not. i have created dummyComponent.js in /src/Component/DummyComponent directory and import in App.js.

17 to minimize development i have copied UI code from mui.com (sample code for components you will see)

Image description

Image description

Image description

16 lets open browser tab to see if everything is working
(http://localhost:3000/)

Actual working of Code

Hope you enjoyed this tutorial. this is my 1st time posting any tutorial in any platform.
let me know your thoughts in comments

github link for project -
https://github.com/quteboy/mui-theme-switcher.git

Top comments (0)