Obsessed with React and teaching. I help people become Frontend Developers. Living with my fiancee and Yorkshire Terrier 🐶 in Poland.
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.
React - useDarkMode.js
React - App.js
- To avoid magic strings we create a
THEMEmapper to keep our string values.
- Then we add
darkModeThemeobjects with CSS properties.
- Additionally, there is a
THEME_MAPPERto map string value to a
useStateto keep track of the currently selected theme string value.
toggleThemeswitches currently selected
- Lastly, we return the
themeobject based on the string value (using
isDarkModeboolean which we'll use in our
GlobalStylescomponent is used to apply CSS to
htmltag based on the selected theme.
- Inside of the
Appcomponent we use our
useDarkModehook 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
- Toggle is created using
Switchcomponent and we assign
- Lastly, we finish the rest of our application with simple HTML tags.
- 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 😅)
THE GUIDE TO BEAT FRONTEND INTERVIEW
Let's build a community that will help each other.