Enable Dark Mode with React and Tailwind thumbnail

Enable Dark Mode with React and Tailwind

A few steps are required to implement dark mode in a React project using Tailwind CSS. I'll give you a high-level overview of the procedure

A few steps are required to implement dark mode in a React project using Tailwind CSS. I'll give you a high-level overview of the procedure:

Make sur that Tailwind is installed and working
check : Setup Tailwind with React


Enable Dark mode :


Step1: Configure Tailwind

Go to tailwind.config.js (tailwind config file) in your project directory and add darkMode: "class" :

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

Step 2: Create useDarkMode Hook:

create a new hook file (ex: useDarkMode.jsx file) to toggle dark mode
also It keeps the user's previous chosen mode in the browser using localStorage so that when the user returns to the page, they may continue with their last selected mode.

useDarkMode.jsx

import { useState, useEffect } from "react";

export default function useDarkMode() {
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 3: Build Dark mode switch button:

we are going to use react-toggle-dark-mode :

DarkModeToggle.jsx
import { useState } from "react";
import { DarkModeSwitch } from "react-toggle-dark-mode";
import useDarkMode from "./useDarkMode";

export default function DarkModeToggle() {
const [colorTheme, setTheme] = useDarkMode();
const [darkMode, setDarkMode] = useState(
colorTheme === "light" ? true : false
);

const toggleDarkMode = (enabled) => {
setTheme(colorTheme);
setDarkMode(enabled);
};

return (
<DarkModeSwitch
style={{ marginBottom: "2rem" }}
checked={darkMode}
onChange={toggleDarkMode}
size={32}
/>
);
}


Step 4 : use the dark mode component:
for example I am going to add it to the app file:

App.jsx
import React from "react";
import DarkModeToggle from "./DarkModeToggle";

function App() {
return (
<main>
<h1>Hello codexpand</h1>
<Switcher />
<main>
);
}

export default App;


Step 5: Start using dark mode classes:

now you are able to use dark mode here is an example :

Component.tsx
<h3 className="text-2xl font-bold text-sky-900 dark:text-white" >
Hello codexpand
</h3>

codecillionlogo

codecillion

Copyright ©2025 , all rights reserved