Mahesh Ghamaand
Mahesh Ghamaand

Reputation: 515

How to change daisyUI theme in nextjs using button click?

According to daisyUI documentation, we can update theme by updating value of data-theme variable in in <html> tage like this: <html data-theme="cupcake"></html>

By looking at nextjs documentation for Custom Document, I could not figure out how to dynamically update data-theme

Upvotes: 1

Views: 1889

Answers (1)

Mahesh Ghamaand
Mahesh Ghamaand

Reputation: 515

We can update data-theme variable on <html> tag in nextjs with the help of npm package next-themes like this:

// _app.tsx
import { ThemeProvider } from "next-themes";

const MyApp = ({
  Component,
  pageProps: { ...pageProps },
}) => {
  return (
      <ThemeProvider>
        <Component {...pageProps} />
      </ThemeProvider>
  );
};

export default MyApp;
// header.tsx
import { MoonIcon, SunIcon } from "@heroicons/react/24/solid";
import { useTheme } from "next-themes";

export default function Header() {
  const { theme, setTheme } = useTheme();

  return (
    <div>
      {theme === "business" ? (
        <div
          className="flex-1 lg:flex-none"
          onClick={() => setTheme("emerald")}
        >
          <SunIcon className="h-8 w-8 cursor-pointer text-green-400 sm:h-10 sm:w-10" />
        </div>
      ) : (
        <div
          className="flex-1 lg:flex-none"
          onClick={() => setTheme("business")}
        >
          <MoonIcon className="h-8 w-8 cursor-pointer text-green-400 sm:h-8 sm:w-8" />
        </div>
      )}
    </div>
  );
}

Next-themes by default changes value of data-theme on <html> tag upon execution of setTheme('value') function

Upvotes: 0

Related Questions