Theme Toggle for Dev

A handy theme toggle button helpful during development to quickly test dark/light themes. It sticks on top of all elements in a convenient position.

theme toggle demo

theme-toggle.tsx

"use client";

import { useTheme } from "next-themes";

import { Icons } from "@/assets/icons";
import { Button } from "@/components/ui/reusables/button";

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

  return (
    <aside>
      <Button
        onClick={() => setTheme(theme === "dark" ? "light" : "dark")}
        className="fixed bottom-3 right-16 z-50 text-foreground"
        size="icon"
        aria-label="toggle theme"
      >
        <Icons.Sun />
      </Button>
    </aside>
  );
}

Usage

// layout.tsx

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="en">
      <body>
          {children}
          {process.env.NODE_ENV === "development" && (
              <ThemeToggleButton />
          )}
      </body>
    </html>
  );
}

Loved this post?

Comments

Interested in
working
with me?