React + Material-UI: Create Dark/Light Theme Toggle

Last updated on May 24, 2021 A Goodman Loading... One comment

Modern web apps often have both a light theme and a dark theme so that users can choose what works best for them. The light theme is suitable for daytime use, while the dark theme is suitable for night use and reduces eye strain as well as saves energy.

This article walks you through a complete example of implementing a light/dark theme toggle in a React application built with Material-UI.

Example Preview

We are going to build a super simple React app that contains a card with some text and a switch inside. When the switch is off, the light theme is used. When the switch is on, the dark theme will be applied.

Here’s how it works:

The Code

1. Create a new React project by executing the command below:

npx create-react-app my_app

2. Installing the required packages:

npm i @material-ui/core @fontsource/roboto

The Roboto font is not be automatically loaded by Material-UI. That’s why we need to add the @fontsource/roboto package.

3. Remove all of the default code in your src/App.js and add the following:

import { useState } from "react";

// Import Material-UI stuff
import "@fontsource/roboto"; // Loading Roboto font. Material-UI was designed with this font in mind.
import {
  ThemeProvider,
  Card,
  CardHeader,
  Switch,
  CardContent,
  Box,
  Container,
  Typography,
  FormGroup,
  FormControlLabel,
  CssBaseline,
} from "@material-ui/core";
import { createMuiTheme } from "@material-ui/core/styles";

// Define theme settings
const light = {
  palette: {
    type: "light",
  },
};

const dark = {
  palette: {
    type: "dark",
  },
};

const App = () => {
  // The light theme is used by default
  const [isDarkTheme, setIsDarkTheme] = useState(false);

  // This function is triggered when the Switch component is toggled
  const changeTheme = () => {
    setIsDarkTheme(!isDarkTheme);
  };

  return (
    <ThemeProvider
      theme={isDarkTheme ? createMuiTheme(dark) : createMuiTheme(light)}
    >
      <CssBaseline />
      <Container>
        <div className="App">
          <Box component="div" p={5}></Box>
          <Card>
            <CardHeader
              action={
                <FormGroup>
                  <FormControlLabel
                    control={
                      <Switch checked={isDarkTheme} onChange={changeTheme} />
                    }
                    label="Dark Theme"
                  />
                </FormGroup>
              }
            />
            <CardContent>
              <Typography variant="h3" component="h3">
                Kindacode.com
              </Typography>
              <Typography variant="body1">
                Dark Mode is {isDarkTheme ? "On" : "Off"}
              </Typography>
            </CardContent>
          </Card>
        </div>
      </Container>
    </ThemeProvider>
  );
};

export default App;

4. Run your project and check the result.

Conclusion

You’ve learned how to switch between dark them and light theme in a React app that uses Material UI. Continue learning more new and interesting things about React by taking a look at the following articles:

You can also check our React topic page and React Native topic page for the latest tutorials and examples.

Related Articles

Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
DarkLord
DarkLord
29 days ago

Nice!

1
0
Would love your thoughts, please comment.x
()
x