Dark mode has become a standard in both mobile and web applications. The sobriety, elegance, and serenity conveyed by dark tones with clear contrasts have led a large number of users to prefer their app to have the option to switch to dark mode.
The implementation of dark mode in an app built with React JS and Tailwind is quite simple. It only requires a couple of configurations in your tailwind.config.js file and building a small logic to detect the theme change from your application.
1. Setting up Tailwind
Open your tailwind.config.js file
In this file, you will find all the configurations corresponding to Tailwind. Here you will add the following property:
darkMode: 'class'
2. Logic in the button that will toggle the mode
To perform the mode switch, we will directly access the DOM
We will use a useState which will change when the button is pressed.
- Definition of useState: It's defined with the name theme and its respective modifier setTheme. It will be of type string and will have the value 'light' by default.
- We define the button that will perform the change:
In the button we'll use to change the theme, we'll use the onClick method to call a function that will change the state called changeTheme (This function can be named as you prefer, for example handleChangeTheme)
- Function that will execute the change: In the changeTheme function, the value of the state theme is changed using a condition established by the conditional operator. If the value of the state is 'light', it will be changed to 'dark', otherwise, the value will be 'light'. This way, we ensure the switch between both values every time the button is clicked. ## 3. Changing the HTML class with useEffect
- Using the useEffect hook, we will add and remove the 'dark' class depending on the content of the theme state: if the content is 'dark', we will add the 'dark' class to our HTML by accessing the DOM, and if the state value is 'light', we will remove that class from the HTML. ## 4. Applying the styles for dark mode. Now, all we need to do is prefix each style we want to apply to dark mode with the word dark: Additionally, we'll have the styles already defined in light mode on the element to which we want to apply these styles, like this: ## Conclusion: This is the way to implement dark mode in an app built with React JS, however, it can be applied to any modern JS framework.
Top comments (2)
Great work on implementing dark mode using Tailwind in React! Your step-by-step guide is clear and easy to follow.👩💻One suggestion I have is to consider using code iframes instead of images for the code snippets. This would make it easier for readers to copy and paste the code directly into their projects, improving the overall usability of your blog.
Keep up the excellent work!
Thank you for your comment, I'm glad it was clear for you. I'll consider your advice into account for next time.