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
THEMEmapper to keep our string values. - Then we add
defaultThemeanddarkModeThemeobjects with CSS properties. - Additionally, there is a
THEME_MAPPERto map string value to athemeobject. useDarkModehook usesuseStateto keep track of the currently selected theme string value.toggleThemeswitches currently selectedthemestring value.- Lastly, we return the
themeobject based on the string value (usingTHEME_MAPPER),toggleThemefunction, andisDarkModeboolean 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.
GlobalStylescomponent is used to apply CSS tohtmltag based on the selected theme.- Inside of the
Appcomponent we use ouruseDarkModehook 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 theGlobalStylescomponent. - Toggle is created using
Switchcomponent 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
useDarkModeand it almost has 1k stars on GitHub, worth checking out.
