Dark Mode Setup For React TypeScript Tailwind Keep-React

Sanjoy Roy
1 min readJan 1, 2025

--

Vite Project Setup

npm create vite@latest my-project -- --template react
cd my-projectn

Tailwind Setup

npm i autoprefixer postcss tailwindcss
npx tailwindcss init -p

Keep-React Setup

npm i keep-react phosphor-react

index.css

@import "keep-react/css";
@tailwind base;
@tailwind components;
@tailwind utilities;

tailwind.config.js

import { keepTheme } from "keep-react/keepTheme";

const config = {

content: ["./index.html", "./src/**/*.{js,ts,jsx,tsx}"],

darkMode: "class",

theme: {},

};

export default keepTheme(config);

NavbarTop.jsx / .tsx

import { Switch } from "keep-react";
import { useEffect, useState } from "react";


const NavbarTop = () => {
const [isDarkMode, setIsDarkMode] = useState(false);

useEffect(() => {

// Dark Mode Check

if (localStorage?.getItem("darkMode") == "on") {
document.body.classList.add("dark");
setIsDarkMode(true);
}

}, []);



// Handle DarkMode Function

const handleDarkMode = () => {

document.body.classList.toggle("dark");

if (isDarkMode) {
localStorage?.removeItem("darkMode");
setIsDarkMode(false);
} else {
localStorage?.setItem("darkMode", "on");
setIsDarkMode(true);
}
};

return
<div className=" text-gray-800 dark:text-gray-100 bg-gray-100 dark:bg-gray-800">
<span className=" flex justify-end p-5 xl:p-8">
<Switch variant="icon"
onCheckedChange={()=>handleDarkMode()} />
</span>
</div>
);
};



export default NavbarTop;

//https://github.com/sanjoy-git

--

--

Sanjoy Roy
Sanjoy Roy

No responses yet