DEV Community

Cover image for Simplest way to implement dark mode in your react + tailwind project

Posted on • Updated on

Simplest way to implement dark mode in your react + tailwind project

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.

Step 1 : Opting into dark mode in tailwind config file

Open your tailwind.config.cjs and add this to your config.

changes to make to tailwind.config.cjs file for opting into darkmode

Step 2 : Writing the logic for dark mode to work

In your hooks folder create a new file named useTheme.js with the following lines of code in it.

useTheme.js file

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.

code snipped for ui which allows users to change theme

Step 3 : Adding styles for dark mode

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 dark:text-neutal-100.

Here is a code snippet for your reference 👇

code snippet for using dark mode in tailwind css

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 👇.

Happy Hacking

Top comments (0)