DEV Community

Cover image for 1-line theme switching in React (with Tailwind + DaisyUI)
Naman Dwivedi
Naman Dwivedi

Posted on • Updated on

1-line theme switching in React (with Tailwind + DaisyUI)

DaisyUI is the best Tailwind components library I have worked with. Although it provides many beautiful preset themes(dark, light, cupcake, bumblebee and many more), the only tricky part was implementing theme switching with daisyUI button or toggle.

In this post I'll show how to implement light and dark mode switching seamlessly.

Although the official tutorial on daisyUI's website says you should use the 'theme-change' npm package, I found it easier to directly add the 'data-theme' attribute to the html tag(which is what the package does).

Here is what the toggle button component code looks like:

const Toggle = () => {
  useEffect(() => {
    /* Sets the data-theme attribute on html tag */
    document.documentElement.setAttribute(
      "data-theme",
      localStorage.getItem("theme") === "dark" ? "dark" : "light"
    );
  }, []);

  return (
     /* Component provided by daisyUI - https://daisyui.com/components/toggle/ */
     <input
       type="checkbox"
       className="toggle"
       defaultChecked={
         typeof window !== "undefined" &&
         localStorage.getItem("theme") === "dark"
       }
       onClick={(e) => {
         let newTheme = e.target.checked ? "dark" : "light";
         localStorage.setItem("theme", newTheme);
         document.documentElement.setAttribute("data-theme", newTheme);
        }}
     />
  );
};
Enter fullscreen mode Exit fullscreen mode

Since I am using NextJS I confirmed whether we are on the client side before accessing localStorage to set the defaultChecked value of the toggle.

And that's it! This will let you use the toggle button to switch themes(with built-in smooth transitions), save your theme to the local storage and use localStorage to restore the theme on further visits to the webpage.

If you wish to use different UI components to switch between themes (i.e. use buttons or a dropdown menu), you can do so in exactly the same way using the respective components from daisyUI.

To implement more themes, all you need is the name of the theme, all the theme configurations come out of the box with daisyUI!

Incredible, isn't it?!

Latest comments (0)