Image by Alex Andrews from Pexels
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
- To avoid magic strings we create a
THEME
mapper to keep our string values. - Then we add
defaultTheme
anddarkModeTheme
objects with CSS properties. - Additionally, there is a
THEME_MAPPER
to map string value to atheme
object. useDarkMode
hook usesuseState
to keep track of the currently selected theme string value.toggleTheme
switches currently selectedtheme
string value.- Lastly, we return the
theme
object based on the string value (usingTHEME_MAPPER
),toggleTheme
function, andisDarkMode
boolean which we'll use in ourApp.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 tohtml
tag based on the selected theme.- Inside of the
App
component we use ouruseDarkMode
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 theGlobalStyles
component. - Toggle is created using
Switch
component and we assignchecked={isDarkMode}
andonChange={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.