VizStats UI

Dark Mode

Follow this comprehensive guide to add dark mode support to your project using VizStats UI components. Our implementation is based on the shadcn/ui approach, providing a seamless and customizable dark mode experience.

Prerequisites

Ensure you have VizStats UI installed in your project. If not, follow the installation guide.


Adding Dark Mode Support


Install Dependencies

Install the necessary dependencies using your preferred package manager:

npm install next-themes

Set Up the Theme Provider

Create a new file called theme-provider.tsx in your components directory: components/theme-provider.tsx

"use client";
 
import * as React from "react";
import { ThemeProvider as NextThemesProvider } from "next-themes";
 
export function ThemeProvider({
  children,
  ...props
}: React.ComponentProps<typeof NextThemesProvider>) {
  return <NextThemesProvider {...props}>{children}</NextThemesProvider>;
}

Then, wrap your app with the ThemeProvider in your layout.tsx file:

import { ThemeProvider } from "@/components/theme-provider";
 
export default function RootLayout({ children }: RootLayoutProps) {
  return (
    <html lang="en" suppressHydrationWarning>
      <head />
      <body>
        <ThemeProvider
          attribute="class"
          defaultTheme="system"
          enableSystem
          disableTransitionOnChange
        >
          {children}
        </ThemeProvider>
      </body>
    </html>
  );
}

Create a Theme Toggle

Create a new component called theme-toggle.tsx in your components directory: components/theme-toggle.tsx

"use client";
 
import { useEffect, useState } from "react";
import { Moon, Sun } from "lucide-react";
import { useTheme } from "next-themes";
 
export function ModeToggle() {
  const { setTheme, theme } = useTheme();
  const [mounted, setMounted] = useState(false);
 
  useEffect(() => {
    setMounted(true);
  }, []);
 
  if (!mounted) return null;
 
  return (
    <button
      className="flex items-center justify-center gap-2 rounded-md border border-input bg-transparent px-4 py-2 text-sm font-medium hover:bg-accent hover:text-accent-foreground"
      onClick={() => setTheme(theme === "dark" ? "light" : "dark")}
    >
      {theme === "dark" ? (
        <Sun className="h-4 w-4" />
      ) : (
        <Moon className="h-4 w-4" />
      )}
      <span>Toggle {theme === "dark" ? "Light" : "Dark"} Mode</span>
    </button>
  );
}

Now, you can easily toggle between light and dark modes using the ThemeToggle component in your UI.

Use the Theme Toggle

In your UI, you can use the ThemeToggle component to toggle between light and dark modes:

import { ModeToggle } from "@/components/theme-toggle";
 
export function Header() {
  return (
    <header>
      {/* Other header content */}
      <ModeToggle /> // [!code ++]
    </header>
  );
}

On this page