How to easily set up Material UI theme toggle in React

full_stack_adi profile image Aditya Originally published at adityanaik.dev on ・1 min read

Scaffold React Application

A new react app is easily scaffolded using

$ npx create-react-app my-app

Install dependencies

I need to install material ui core package.

// with npm

$ npm install @material-ui/core

// with yarn

$ 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.

  • Add Light and Dark themes

export const light = {

  palette: {

  type: 'light',



export const dark = {

  palette: {

  type: 'dark',



  • Import ThemeProvider and createMuiTheme

import { ThemeProvider } from '@material-ui/core'

import { createMuiTheme } from '@material-ui/core/styles'

  • Set up the toggle logic

const [theme, setTheme] = useState(true)

const icon = !theme ? <Brightness7Icon /> : <Brightness3Icon /> 
// Icons imported from `@material-ui/icons`

const appliedTheme = createMuiTheme(theme ? light : dark)

  • Wrap the render inside ThemeProvider and pass the appliedTheme

return (

 <ThemeProvider theme={appliedTheme}>

 //rest of the code



  • Trigger toggle using onClick

 onClick={() => 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.

Posted on Jun 20 by:

full_stack_adi profile



Full Stack Developer #React #Rails #Express


markdown guide