Add MUI v5 Theme Switcher in NextJs/React
Tags: react, nextjs, javascript, tutorial
Published: 2023-05-27 13:03:52

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
```

2. Install MUI-v5 UI library and supporting dependencies


```
npm install @mui/material @emotion/react @emotion/styled js-cookie
```
3. Lets run the app by hitting the following command


```
npm start 
```
4. 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nnwtb9enz7co3n8ztx9a.png)

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

![AppbarJs file with Select Dropdown](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/429f7fr26uqi64ygqs56.png)
8. 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8hiivmlyila3agvjswda.png)

9. 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lop0a7cpp8jl108v81rg.png)

10. 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;

```
11. after adding above code your `App.js` **your file should look like this**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v0vnti58jpxsnljfpx14.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bb8l0q8bjlzo4664i9bx.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/64hb6gtezjvmz7edoj3c.png)

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 .
13. your `Themes` folder should look like


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gfybtrwlkrftra20d0bq.png)

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;

```

15.`Navbar.js` should look like this

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hcx1v9i133mltw8z9t4q.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f8r3fpczw12kyomner0o.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2cc0gpi5meika2gou58a.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2dhxy1ab2jpvx2r0d0l3.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oalgkmsy3xb5ays41hat.png)

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

![Actual working of Code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k94yv75zf0mj3sxdnl0u.png)

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