Dark Mode Toggle

Utility

Light and dark mode switch button.

Preview

Toggle dark mode

Usage

example.jsx
import { DarkModeToggle } from "@/components/ui/dark-mode-toggle";

export default function Example() {
  return <DarkModeToggle />;
}

Source Code

Copy this file into components/ui/dark-mode-toggle.jsx in your project.

dark-mode-toggle.jsx
"use client";

import { forwardRef, useState, useEffect } from "react";
import { cn } from "@/lib/utils";

const DarkModeToggle = forwardRef(({ className, ...props }, ref) => {
  const [dark, setDark] = useState(false);
  useEffect(() => { setDark(document.documentElement.classList.contains("dark")); }, []);
  const toggle = () => {
    const next = !dark;
    setDark(next);
    document.documentElement.classList.toggle("dark", next);
    document.documentElement.classList.toggle("light", !next);
  };
  return (
    <button ref={ref} onClick={toggle}
      className={cn("inline-flex h-9 w-9 items-center justify-center rounded-md border transition-colors hover:bg-accent", className)}
      aria-label="Toggle dark mode" {...props}
    >
      {dark ? (
        <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><circle cx="12" cy="12" r="5" strokeWidth={2} /><path strokeWidth={2} d="M12 1v2m0 18v2M4.22 4.22l1.42 1.42m12.72 12.72l1.42 1.42M1 12h2m18 0h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42" /></svg>
      ) : (
        <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 12.79A9 9 0 1111.21 3 7 7 0 0021 12.79z" /></svg>
      )}
    </button>
  );
});
DarkModeToggle.displayName = "DarkModeToggle";

export { DarkModeToggle };

Quick Install

Make sure you have the cn() utility set up. It requires clsx and tailwind-merge.

npm install clsx tailwind-merge