Skip to content

Aditya Naik

How to easily set up Material UI theme toggle in React

React, theme, CSS, Material UI1 min read

Scaffold React Application

A new react app is easily scaffolded using

1$ npx create-react-app my-app

Install dependencies

I need to install material ui core package.

1// with npm
2$ npm install @material-ui/core
3
4// with yarn
5$ yarn add @material-ui/core

Wrap application in Theme Provider

For the purpose of this demo, I will use App.js to set up everything.

  1. Add Light and Dark themes
1export const light = {
2 palette: {
3 type: 'light',
4 },
5}
6export const dark = {
7 palette: {
8 type: 'dark',
9 },
10}
  1. Import ThemeProvider and createMuiTheme
1import { ThemeProvider } from '@material-ui/core'
2import { createMuiTheme } from '@material-ui/core/styles'
  1. Set up the toggle logic
1const [theme, setTheme] = useState(true)
2const icon = !theme ? <Brightness7Icon /> : <Brightness3Icon /> // Icons imported from `@material-ui/icons`
3const appliedTheme = createMuiTheme(theme ? light : dark)
  1. Wrap the render inside ThemeProvider and pass the appliedTheme
1return (
2<ThemeProvider theme={appliedTheme}>
3 //rest of the code
4 </ThemeProvider>
5)
  1. Trigger toggle using onClick
1onClick={() => setTheme(!theme)}

Now our theme toggle logic is in place.

Add rest of the material ui components and see the toggle in action!

You can see a working example here, along with the code.

© 2020 by Aditya Naik. All rights reserved.