Overview
Get Started
Next.js - Dark Mode
Adding dark mode to your next app.
Install next-themes
Start by installing next-themes:
pnpm add next-themes
Create a theme provider
"use client";
import { ThemeProvider as NextThemeProvider } from "next-themes";
export function ThemeProvider({
children,
...props
}: React.ComponentProps<typeof NextThemeProvider>) {
return (
<NextThemeProvider
attribute="class"
defaultTheme="system"
disableTransitionOnChange
enableColorScheme
enableSystem
{...props}>
{children}
</NextThemeProvider>
);
}Wrap your root layout
Add the ThemeProvider to your root layout and add the suppressHydrationWarning prop to the html tag.
import { ThemeProvider } from "@/providers/theme-provider";
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en" suppressHydrationWarning>
<body>
<ThemeProvider>{children}</ThemeProvider>
</body>
</html>
);
}Add a theme toggle
Place a theme toggle on your site to toggle between light and dark mode.
"use client";
import { useTheme } from "next-themes";
import { IconMoonStars, IconSunHighFilled } from "@tabler/icons-react";
import { Button } from "@/components/ui/button";
export function ThemeToggle() {
const { setTheme, resolvedTheme } = useTheme();
const toggleTheme = () => {
setTheme(resolvedTheme === "dark" ? "light" : "dark");
};
return (
<Button className="relative size-8" onClick={toggleTheme} size="icon" variant="ghost">
<IconMoonStars className="absolute size-4 transition-opacity dark:opacity-0" />
<IconSunHighFilled className="absolute size-4 opacity-0 transition-opacity dark:opacity-100" />
<span className="sr-only">Toggle theme</span>
</Button>
);
}