Github just rolled out dark mode for their website last week. It has been a trend for quite some time and the dark settings are easier to the eyes. There are obviously a lots of ways to achieve a dark look for any given websites but I wanted to learn how to implement the dark mode in a React app and using material ui and It’s really quite easy to achieve dark mode and toggle it between dark and light mode using react hooks and material ui. Just for simplicities sake I will try to explain the process with a React project that has bare minimum of code in it.
First I created a brand new React project using create-react-app.
$ npx create-react-app my-app
Then installed material-ui to the project.
$ npm install @material-ui/core
After getting rid of most of the files that comes with the scaffolding I ended up with just a div in my app that showed this.
The goal was to have a toggle in the page that would switch the theme between dark and light. So, In my app.js I imported ThemeProvider and createMuiTheme from material-ui and imported useState from React. I wrapped the application in ThemeProvider first.
createMuiTheme provides a property called palette which has a type property and by looking at the browser console I could see it has a value of ‘light’. So I just needed to change it to ‘dark’.
I saved the theme object to a variable and provided it to the theme provider and at this point my app.js looked like this.
I created two more variable called light and dark that had palette type of light and dark respectively. I also added state to the app components to manage the theme state and default it to ‘true’ so I can use the boolean to toggle between the state.
I refactored my currentTheme variable using a ternary expression to toggle between the palette types. After that I needed a button or icon that would trigger an event that in turn would change the current theme type. I decided to use Material ui icons. So I had to install the materail ui icon package.
$ npm install @material-ui/icons
After importing the icons my app.js looked like this.
And that’s how the page looked.
After that I just used an anonymous function to toggle between the theme state.
At this point I could see the click event happening whenever I clicked on the icon on the page but it seemed unchanged. After a few moments of looking around I found out that I needed to use the CssBaseLine components from material-ui to actually keep the styling in sync with our theme. After importing CssBaseLine from material ui and using it inside the app I could toggle between the dark mode and light mode easily. This is how my app.js finally looked like.
And the browser looked like this after the dark mode on.
I hope this helps if anyone looking to quickly implement dark mode in a React app. Any suggestions will be appreciated. Thank you for reading.