Skip to main content

Command Palette

Search for a command to run...

TailwindCSS Dark Mode, Day Mode, System Mode website

Updated
2 min readView as Markdown
M

Hi, I am Full Stack Developer. I can build web application, android application, desktop application. My core programming language is JavaScript.

Step 1: In project folder open index.html and in `<body> tag add this class:

className="dark"

Example:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite + React</title>
  </head>
  <body className="dark">
    <div id="root"></div>
    <script type="module" src="/src/main.jsx"></script>
  </body>
</html>

Step 2) in project folder open tailwind.config.js file and type this :

darkMode: "class"

Example:

/** @type {import('tailwindcss').Config} */
export default {
  content: ["./index.html", "./src/**/*.{js,ts,jsx,tsx}"],
  darkMode: "class",
  theme: {
    extend: {      
    },
  },
  plugins: [],
};

Step 3) Where your Dark mode button type this code:

  const [theme, setTheme] = useState(null);

  useEffect(() => {
    if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
      setTheme("dark");
    } else {
      setTheme("light");
    }
  }, []);

  useEffect(() => {
    if (theme === "dark") {
      document.documentElement.classList.add("dark");
    } else {
      document.documentElement.classList.remove("dark");
    }
  }, [theme]);

 const handleThemeSwitch = () => {
    setTheme(theme === "dark" ? "light" : "dark");
  };

Example


const Sidebar = ({ menu, setMenu }) => {
  const [theme, setTheme] = useState(null);

  useEffect(() => {
    if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
      setTheme("dark");
    } else {
      setTheme("light");
    }
  }, []);

  useEffect(() => {
    if (theme === "dark") {
      document.documentElement.classList.add("dark");
    } else {
      document.documentElement.classList.remove("dark");
    }
  }, [theme]);

  const handleThemeSwitch = () => {
    setTheme(theme === "dark" ? "light" : "dark");
  };

  return (
    <>
       <div className="">
          <button className="" onClick={handleThemeSwitch}>
              {theme === "dark" ? <OnButton /> : <OffButton />}
           </button>
       </div>  
    </>
  );
};

export default Sidebar;
8 views

More from this blog

promahbubul

63 posts

I'm React Native and Full Stack Web Deveioper. My core programming language is JavaScript.