Saturday, November 16, 2024
Google search engine
HomeLanguagesHow to Add Dark Mode in ReactJS using Tailwind CSS ?

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.

In this article, we’ll see how to add dark mode in the ReactJS project using Tailwind CSS. Dark mode is very popular nowadays and becoming more and more common to design a dark version of our website to go along with the default web design. To make your website use dark mode, tailwind provides a ‘dark’ variant that helps in styling our website differently when dark mode is enabled.

Step for Creating React Application And Installing Module:

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 install -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: It will look like the following. 

 

Syntax: To add the dark mode in react using tailwind, we just have to prefix dark: to the CSS classes. See the syntax below for a better understanding.

<div className="bg-gray-100 dark:bg-white">
    <h1 className="text-black dark:text-white">
        neveropen
    </h1>
</div>

Example: Below example demonstrates the dark mode in React.js using tailwind CSS. In the given example, we have developed a basic card component for implementing dark mode support. Here, when the switcher component gets triggered, the whole webpage gets changed to dark/light theme. Apart from this, If the user refreshes the page, the user continues to see the last changed theme preference as it we have used local storage to save the user’s browser preference.

Steps for adding a Toggle button to toggle dark/light theme:

Step 1: Create a Hook to catch the theme changes. It also saves the last preferred mode of the user in the browser using localStorage and whenever the user visits the website again, they can continue with their last preferred mode.

useDarkSide.js file

Javascript




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


Step 2: Create an Event (Switcher component) to trigger the theme-changing hook.

Switcher.js file

Javascript




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}
            />
        </>
    );
}


Step 3: Add the Switcher component file to the App.js file.

App.js

Javascript




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">
                    neveropen
                </h1>
                <h3 className="text-black dark:text-white text-2xl">
                    Adding Dark Mode in ReactJS using Tailwind CSS
                </h3>
            </div>
            <center>
                <Switcher />
                <div class="w-56 overflow-hidden bg-white
                rounded-lg border border-gray-200
                shadow-md dark:bg-gray-800 dark:border-gray-700">
                    <img
                        class="rounded-t-lg"
                        src=
                        alt="gfg"
                    />
                    <div class="p-5">
                        <a href="##">
                            <h5 class="mb-2 text-2xl
                            font-bold tracking-tight
                            text-gray-900 dark:text-white">
                                neveropen
                            </h5>
                        </a>
                        <p class="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;


Step to run the application: 

npm start

Output:

 

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments