Open In App

How to Add Dark Mode in ReactJS using Tailwind CSS ?

Tailwind CSS is a CSS framework that helps in building rapid custom UI. It is a highly customizable, low-level CSS framework that gives you all of the building blocks that you need. Tailwind CSS creates small utilities with a defined set of options enabling easy integration of existing classes directly into the HTML code.

Prerequisites:

Approach:

To Add Dark Mode in ReactJS using Tailwind CSS we will be using tailwind classes in the application. Tailwind provides a ‘dark’ variant that helps in styling our website differently when dark mode is enabled. It adds the functionality to switch between light and dark modes.



Creating React Application

Step 1: Create a React application using the following command:

npm create-react-app appname

Step 2: After creating your project folder i.e. folder name, move to it using the following command:



cd foldername

Step 3: After creating the React.js application, install the Tailwind CSS using the following command.

npm i -D tailwindcss postcss autoprefixer
npx tailwindcss init -p

Step 4: Configure template paths and add a class in a dark mode in tailwind.config.js file using the following command:

module.exports = {
content: [
"./src/**/*.{js,jsx,ts,tsx}",
],
darkMode: "class",
}

Step 5: Install a Sun/Moon Icon animation module for transition with React.

npm i react-toggle-dark-mode

Project Structure

Project Structure will look like the following. 

The Updated list of dependencies after installing required modules

{
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"react-toggle-dark-mode": "^1.1.1",
"web-vitals": "^2.1.4"
},
"devDependencies": {
"autoprefixer": "^10.4.16",
"postcss": "^8.4.31",
"tailwindcss": "^3.3.5"
}
}

Example: This example demonstrate the dark mode which is enabled when the button is clicked. This data is stored in the localStorage to store the user preference of web app theme.




// Filename - App.js
 
import React from "react";
import Switcher from "./Components/Switcher";
 
function App() {
    return (
        <div>
            <div style={{ textAlign: "center" }}>
                <h1 className="text-green text-3xl font-bold">
                    GeeksforGeeks
                </h1>
                <h3 className="text-black dark:text-white text-2xl">
                    Adding Dark Mode in ReactJS using
                    Tailwind CSS
                </h3>
            </div>
            <center>
                <Switcher />
                <div
                    className="w-56 overflow-hidden bg-white
                rounded-lg border border-gray-200
                shadow-md dark:bg-gray-800 dark:border-gray-700"
                >
                    <img
                        className="rounded-t-lg"
                        src=
                        alt="gfg"
                    />
                    <div className="p-5">
                        <a href="##">
                            <h5
                                className="mb-2 text-2xl
                            font-bold tracking-tight
                            text-gray-900 dark:text-white"
                            >
                                GeeksforGeeks
                            </h5>
                        </a>
                        <p
                            className="mb-3 font-normal text-gray-700
                            dark:text-gray-400"
                        >
                            Best coding website for
                            developers in the world.
                        </p>
                    </div>
                </div>
            </center>
        </div>
    );
}
 
export default App;




// Filename - Components/Switcher.js
 
import { useState } from "react";
import { DarkModeSwitch } from "react-toggle-dark-mode";
import useDarkSide from "../hooks/useDarkSide";
 
export default function Switcher() {
    const [colorTheme, setTheme] = useDarkSide();
    const [darkSide, setDarkSide] = useState(
        colorTheme === "light" ? true : false
    );
 
    const toggleDarkMode = (checked) => {
        setTheme(colorTheme);
        setDarkSide(checked);
    };
 
    return (
        <>
            <DarkModeSwitch
                style={{ marginBottom: "2rem" }}
                checked={darkSide}
                onChange={toggleDarkMode}
                size={30}
            />
        </>
    );
}




// Filename - hooks/useDarkSide.js
 
import { useState, useEffect } from "react";
 
export default function useDarkSide() {
    const [theme, setTheme] = useState(localStorage.theme);
    const colorTheme = theme === "dark" ? "light" : "dark";
    localStorage.setItem("theme", theme);
    useEffect(() => {
        const root = window.document.documentElement;
        root.classList.remove(colorTheme);
        root.classList.add(theme);
        if (localStorage.theme == "dark")
            localStorage.removeItem("theme");
        else localStorage.setItem("theme", theme);
    }, [theme, colorTheme]);
 
    return [colorTheme, setTheme];
}

Step to run the application: Use this command in the terminal inside the project directory.

npm start

Output: This output will be visible on the http://localhost:3000/ on the browser window.


Article Tags :