Dark Mode in Tailwind CSS: A Simple Two-Step Process

Chandrakethan
3 min readFeb 15, 2024

--

Almost every website you encounter nowadays offers both dark mode and light mode options. Implementing these modes can be challenging, but fear not — Tailwind CSS is here to save the day. Tailwind CSS is a utility-first CSS framework that provides low-level utility classes to style your HTML directly, allowing for rapid development and customisation without writing traditional CSS stylesheets.

In this article, I’ll cover how you can add a dark mode feature to your React application, complete with source code.

TailwindCSS

Note: If you already know how to install Tailwind and know how to create a react app skip to 5th step.

Steps:

  1. First, create a React app by running the following command:
npx-create-react-app "app-name"

2. Switch to your created React app directory from the terminal using:

cd app-name.

3. Install Tailwind CSS by running these commands in the terminal:

npm install -D tailwindcss
npx tailwindcss init

4. Add the CSS import statements to the ‘index.css’ file:

@tailwind base;
@tailwind components;
@tailwind utilities;

5. You can find ‘tailwind.config.js’ after installing tailwind css in that make these changes

tailwind config file

Note: If you use ‘.js’ extension for your react app, replace ‘.jsx’ with ‘.js’ inside the content.

6. Then, go to the ‘index.html’ file available in the public folder and add the className =’dark’ to the body like this.

That’s it !

Now, all you have to do is make changes to your ‘app.jsx’ file to define how it should appear in light and dark mode. There are some necessary functions for switching between modes. Using the useState hook, you can handle the theme of the webpage, and the useEffect hook is responsible for toggling the theme from light to dark or vice versa. Using the ‘dark’ variant you can customise each component in your website. This is a simple implementation of light mode and dark mode.

simple lightmode and darkmode implementation

The output changes when you click the switch button, toggling between light mode and dark mode, and vice versa.

Left side is the ‘light mode’ and Right side is the ‘dark mode’.

Here’s the source code: https://github.com/chandrakethan27/Dark-Mode

Here’s the documentation about dark mode from Tailwind Css: https://tailwindcss.com/docs/dark-mode

Hope you’ve understood how easy it is to implement the Dark mode. For more such blogs follow me :)

Follow me on:- Instagram , Twitter, GitHub and LinkedIn.

--

--

Chandrakethan

3rd-year Btech IT undergrad 🎓 | Python, JavaScript, Java enthusiast | MERN stack developer 💻 | Let's code and explore together! 🚀