Obsessed with React and teaching. I help people become Frontend Developers. Living with my fiancee and Yorkshire Terrier 🐶 in Poland.
Discover Mentorship
The above is an affiliate link, if you buy the book I'll get a small commission at no extra charge to you.
Obsessed with React and teaching. I help people become Frontend Developers. Living with my fiancee and Yorkshire Terrier 🐶 in Poland.
The above is an affiliate link, if you buy the book I'll get a small commission at no extra charge to you.
Home/Pills/ Pill - React Dark Mode hook/
Home/Pills/Pill - React Dark Mode hook/
Image by Alex Andrews from Pexels

React Dark Mode hook

Feb 1, 2021

DESCRIPTION

We'll create useDarkMode hook to switch between light and dark themes. Our application will be built on top of styled-components and the Material UI Switch component.

Preview

Switch themes

React - useDarkMode.js
  • To avoid magic strings we create a THEME mapper to keep our string values.
  • Then we add defaultTheme and darkModeTheme objects with CSS properties.
  • Additionally, there is a THEME_MAPPER to map string value to a theme object.
  • useDarkMode hook uses useState to keep track of the currently selected theme string value.
  • toggleTheme switches currently selected theme string value.
  • Lastly, we return the theme object based on the string value (using THEME_MAPPER), toggleTheme function, and isDarkMode boolean which we'll use in our App.js.
React - App.js
  • We're using styled-components, Material UI Switch Component, and a little bit of JSX to create our example application.
  • GlobalStyles component is used to apply CSS to html tag based on the selected theme.
  • Inside of the App component we use our useDarkMode hook to get all 3 previously mentioned properties.
  • Then, we supply the currently selected theme to the ThemeProvider, thanks to that, the theme can be used in the GlobalStyles component.
  • Toggle is created using Switch component and we assign checked={isDarkMode} and onChange={toggleTheme} to it.
  • Lastly, we finish the rest of our application with simple HTML tags.

Summary

  • We created a simple theme switcher application using less than 100 lines of code.
  • Feel free to extend the number of themes and create some theme selector to practice a little bit more.
  • Combining various tools can speed up the development process like crazy. (use with caution 😅)
  • Apparently, there is an existing implementation of useDarkMode and it almost has 1k stars on GitHub, worth checking out.
THE GUIDE TO BEAT FRONTEND INTERVIEW
From time to time, I'll send you messages about new blog posts, knowledge pills, and mentoring promotions. Only valuable information, no spam included. You can unsubscribe at any time.
slack
Let's build a community that will help each other.
spread the word
You don't need to, it's okay...