DEV Community

Sagar Roy
Sagar Roy

Posted on

Tailwindcss Dark mode and Light mode Toggle in Reactjs

Implement Dark mode and light mode with TailwindCSS.

  • Copy & paste this code in public/index.html
    <script>
     const defaultTheme = "dark";
      if (!localStorage.getItem("theme")) {
        localStorage.setItem("theme", defaultTheme);
      }
      if (localStorage.getItem("theme") === "dark") {
        document.documentElement.classList.add("dark");
      } else {
        document.documentElement.classList.remove("dark");
      }
    </script>
Enter fullscreen mode Exit fullscreen mode
  • Create a function anywhere in your react project with this code👇
  const toggleTheme = () => {
    const theme = localStorage.getItem("theme"); 
    if (theme === "dark") {
      document.documentElement.classList.remove("dark");
      localStorage.setItem("theme", "light");
    } else {
      document.documentElement.classList.add("dark");
      localStorage.setItem("theme", "dark");
    }
  };
Enter fullscreen mode Exit fullscreen mode
  • Now you can use toggleTheme function.

NOTE: in this example default theme is dark if you don't like dark as default then you can set the light theme as default.
just change defaultTheme variable value dark to light.

Top comments (0)