Switch themes with a class, avoid the flash, and customise dark colours.
On this page
Dark mode is switched by a class or data attribute, the same convention Tailwind uses. Add class="dark" or data-theme="dark" to <html>, or to any wrapper to theme just that part of the page.
"use client";
import { IconButton } from "@kivu-ui/react";
export function ThemeToggle() {
return (
<IconButton
aria-label="Toggle dark mode"
variant="ghost"
onClick={() => {
const dark = document.documentElement.classList.toggle("dark");
localStorage.setItem("theme", dark ? "dark" : "light");
}}
>
🌙
</IconButton>
);
}Apply the saved theme before the page paints. In Next.js, use a beforeInteractive script in the root layout:
import Script from "next/script";
const themeScript = `try{var t=localStorage.getItem("theme");if(t==="dark"||(!t&&matchMedia("(prefers-color-scheme: dark)").matches))document.documentElement.classList.add("dark")}catch(e){}`;
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en" suppressHydrationWarning>
<body>
<Script id="theme" strategy="beforeInteractive">{themeScript}</Script>
{children}
</body>
</html>
);
}.dark {
--kivu-bg: #0a131a;
--kivu-surface: #152431;
--kivu-primary: var(--kivu-primary-300);
}With the Tailwind preset, dark: utilities follow the same switch, so dark:bg-primary-900 just works.