DEV Community

Aditya
Aditya

Posted on • Originally published at adityanaik.dev on

8 2

How to easily set up Material UI theme toggle in React

Scaffold React Application

A new react app is easily scaffolded using


$ npx create-react-app my-app

Enter fullscreen mode Exit fullscreen mode

Install dependencies

I need to install material ui core package.


// with npm

$ npm install @material-ui/core



// with yarn

$ yarn add @material-ui/core

Enter fullscreen mode Exit fullscreen mode

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',

  },

}

Enter fullscreen mode Exit fullscreen mode
  • Import ThemeProvider and createMuiTheme

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

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

Enter fullscreen mode Exit fullscreen mode
  • 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)

Enter fullscreen mode Exit fullscreen mode
  • Wrap the render inside ThemeProvider and pass the appliedTheme

return (

 <ThemeProvider theme={appliedTheme}>

 //rest of the code

 </ThemeProvider>

)

Enter fullscreen mode Exit fullscreen mode
  • Trigger toggle using onClick

 onClick={() => setTheme(!theme)}

Enter fullscreen mode Exit fullscreen mode

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.

Top comments (1)

Collapse
 
sachinchaurasiya profile image
Sachin Chaurasiya

Thanks, man!

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, cherished by the supportive DEV Community. Coders of every background are encouraged to bring their perspectives and bolster our collective wisdom.

A sincere “thank you” often brightens someone’s day—share yours in the comments below!

On DEV, the act of sharing knowledge eases our journey and forges stronger community ties. Found value in this? A quick thank-you to the author can make a world of difference.

Okay