Having dark mode in your website is essential nowadays. In this blog post I will show you how to implement dark mode in your react + tailwind app. This involves 3 simple steps.
tailwind.config.cjs and add this to your config.
In your hooks folder create a new file named
useTheme.js with the following lines of code in it.
This code takes user's preferred theme into account and it also stores the theme state in browser's localStorage so that preferred theme is persisted between different sessions. So feel free to copy this and paste it in
useTheme.js file which we have created.
Next use this
theme state and
toggleTheme function to make an ui so that your users can switch between different theme options. I used icons from react-icons to achieve this.
This is the final step for implementing dark mode in your app. Define the classNames you want to use when theme is set to dark with a prefix
dark:. For example if you want to use text-neutral-100 className in dark mode use
Here is a code snippet for your reference 👇
Since I have added
dark:bg-dark-background to my root div, when users change their preferred theme to dark either by using the ui we created in step 2 or by changing their preferred theme in browser bg-dark-background className is added to my root div. I have defined dark-background with the value
#141414 in my
tailwind.config.cjs file which makes the background of my root div to
#141414. Add necessary styles to all the elements on your app and you are good to go.
Woohoo 🥳🎉 You have managed to add dark mode to your app. Don't forget to share your opinions on this article down in the comments 👇.