Tailwind CSS manual dark mode in react js

3 months agoa minute read

Config

To enable the manual dark mode feature in your tailwindcss website first add darkMode: 'class' in your tailwind.config.js file

tailwind.config.js
jsmodule.exports = {
    darkMode: "class", 
    ... 
}

Hook

Then we have to create a custom hook for getting the current theme and toggling the theme.

jsimport { useEffect, useState } from "react";

export const useTheme = () => {
  const [mode, setMode] = useState("light");

  function changeTheme() {
    const html = document.documentElement;

    if (mode == "light") {
      html.classList.remove("light");
      html.classList.add("dark");
      setMode("dark");
      localStorage.setItem("mode", "dark");
    } else {
      html.classList.remove("dark");
      html.classList.add("light");
      setMode("light");
      localStorage.setItem("mode", "light");
    }
  }

  useEffect(() => {
    const currentMode = localStorage.getItem("mode") || "light";
    document.documentElement.classList.add(currentMode);
    setMode(currentMode);
  }, []);

  return { changeTheme, mode }
};

Import and use

Finally, we can import the useTheme hook in any of our components and bind the changeTheme function with a button or any element. Whenever we call the changeTheme function it will change the website's theme to the opposite.

jsfunction ThemeButton() {
    const { changeTheme } = useTheme()

    return (
        <button onClick={changeTheme}>Change Theme</button>
    )
}

If you understand Bengali then watch this

ShahriyarAlam

Copythight © All Rights Reserved.