DEV Community

Abdulkudus Akanji
Abdulkudus Akanji

Posted on

Next.js Dark Mode: shadcn/ui & Tailwind CSS Setup Guide

Creating a dynamic user interface that adapts to user preferences is a hallmark of modern web development. Implementing a robust light and dark mode is not just about aesthetics; it significantly enhances accessibility and user experience. When building applications with Next.js and shadcn/ui, you're already set up for success in this regard, as shadcn/ui provides excellent integration with Tailwind CSS and theme management.

This guide will walk you through setting up and customizing light and dark modes in your Next.js application using shadcn/ui, covering everything from initial setup to advanced styling adjustments.

Initial Setup: Next.js, shadcn/ui, and next-themes

If you're starting a new project, setting up dark mode is often a pleasant surprise – it's largely handled for you. Let's briefly recap the standard setup process:

  1. Create a Next.js Project: If you haven't already, start with a new Next.js project.

    npx create-next-app@latest my-app
    cd my-app
    
  2. Initialize shadcn/ui: Add shadcn/ui to your project. During initialization, shadcn/ui will prompt you for several configurations. Crucially, it will ask about setting up a ThemeProvider (using next-themes) and will automatically generate the necessary files.

    npx shadcn-ui@latest init
    

    When prompted, ensure you select to configure the ThemeProvider. This action installs the next-themes library and creates a components/theme-provider.tsx file (or similar, depending on your choices) and integrates it into your app/layout.tsx.

How next-themes Works with shadcn/ui

shadcn/ui leverages the popular next-themes library to manage theme state. next-themes smartly handles:

  • System Preference: Automatically detects the user's system theme preference (light or dark).
  • Persistence: Saves the user's chosen theme in localStorage so it persists across sessions.
  • Flash Prevention: Minimizes the "flash of unstyled content" (FOUC) that can occur when themes are applied.

After initialization, your app/layout.tsx will likely look something like this, wrapping your application with the ThemeProvider:

// app/layout.tsx
import type { Metadata } from 'next';
import { Inter } from 'next/font/google';
import './globals.css';
import { ThemeProvider } from '@/components/theme-provider'; // Adjust path if needed

const inter = Inter({ subsets: ['latin'] });

export const metadata: Metadata = {
  title: 'Create Next App',
  description: 'Generated by create next app',
};

export default function RootLayout({
  children,
}: { 
  children: React.ReactNode 
}) {
  return (
    <html lang="en" suppressHydrationWarning>
      <body className={inter.className}>
        <ThemeProvider
          attribute="class"
          defaultTheme="system"
          enableSystem
          disableTransitionOnChange
        >
          {children}
        </ThemeProvider>
      </body>
    </html>
  );
}
Enter fullscreen mode Exit fullscreen mode

Notice the ThemeProvider props:

  • attribute="class": next-themes will add a dark class to the <html> element when dark mode is active. Tailwind CSS then uses this class to apply dark: variants.
  • defaultTheme="system": The initial theme will be based on the user's operating system preference.
  • enableSystem: Allows the theme to switch automatically if the system theme changes.
  • disableTransitionOnChange: Prevents unwanted CSS transitions when the theme changes, leading to a smoother experience.

Tailwind CSS and CSS Variables

shadcn/ui uses CSS variables to define its color palette. These variables are declared in your app/globals.css file, with a separate set of variables under the .dark class for dark mode. This setup allows Tailwind CSS to dynamically apply colors based on the active theme.

/* app/globals.css snippet */
@tailwind base;
@tailwind components;
@tailwind utilities;

@layer base {
  :root {
    --background: 0 0% 100%;
    --foreground: 222.2 84% 4.9%;
    /* ... other light mode variables ... */
  }

  .dark {
    --background: 222.2 84% 4.9%;
    --foreground: 210 20% 98%;
    /* ... other dark mode variables ... */
  }
}
Enter fullscreen mode Exit fullscreen mode

Creating a Theme Toggle Component

Now that the infrastructure is in place, let's create a simple component to allow users to manually switch between themes. We'll use the useTheme hook provided by next-themes.

Create a new file, components/theme-toggle.tsx:

// components/theme-toggle.tsx
'use client'; // This component needs client-side interactivity

import * as React from 'react';
import { useTheme } from 'next-themes';
import { Button } from '@/components/ui/button'; // Assuming you've added a Button component via shadcn/ui
import { Moon, Sun } from 'lucide-react'; // Example icons, install lucide-react if needed

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

  // To avoid hydration mismatch errors, render UI only after component mounts
  const [mounted, setMounted] = React.useState(false);
  React.useEffect(() => setMounted(true), []);

  if (!mounted) return null;

  return (
    <Button
      variant="ghost"
      size="sm"
      onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}
    >
      {theme === 'light' ? (
        <Sun className="h-[1.2rem] w-[1.2rem]" />
      ) : (
        <Moon className="h-[1.2rem] w-[1.2rem]" />
      )}
      <span className="sr-only">Toggle theme</span>
    </Button>
  );
}
Enter fullscreen mode Exit fullscreen mode

Note: You'll need to install lucide-react (npm install lucide-react) and add the Button component via npx shadcn-ui@latest add button if you haven't already. The 'use client' directive is essential for client-side hooks like useTheme.

You can then import and use this ThemeToggle component anywhere in your application, for example, in a header or navigation bar.

Customizing Your Themes

shadcn/ui's approach using CSS variables makes theme customization incredibly flexible. You can easily adjust existing colors or introduce new ones.

Modifying Existing Colors

To change the default background, foreground, primary, or any other color defined by shadcn/ui, simply modify the corresponding CSS variables in app/globals.css.

For example, to change the primary color to a custom blue in light mode and a darker blue in dark mode:

/* app/globals.css */
@layer base {
  :root {
    --background: 0 0% 100%;
    --foreground: 222.2 84% 4.9%;
    --primary: 210 100% 50%; /* A vibrant blue for light mode */
    --primary-foreground: 210 20% 98%;
    /* ... other light mode variables ... */
  }

  .dark {
    --background: 222.2 84% 4.9%;
    --foreground: 210 20% 98%;
    --primary: 210 80% 30%; /* A darker blue for dark mode */
    --primary-foreground: 210 20% 98%;
    /* ... other dark mode variables ... */
  }
}
Enter fullscreen mode Exit fullscreen mode

The values 210 100% 50% are HSL (Hue, Saturation, Lightness) values. You can use any HSL, RGB, or hex color, but HSL is often preferred for theme generation as it's easy to adjust lightness for dark/light variations while maintaining hue and saturation.

Adding New Custom Colors

If you need colors beyond shadcn/ui's defaults, you can define your own CSS variables and integrate them with Tailwind CSS.

  1. Define CSS Variables in globals.css:

    /* app/globals.css */
    @layer base {
      :root {
        /* ... existing variables ... */
        --my-custom-accent: 30 100% 50%; /* Orange for light mode */
      }
    
      .dark {
        /* ... existing variables ... */
        --my-custom-accent: 30 80% 35%; /* Darker orange for dark mode */
      }
    }
    
  2. Extend Tailwind CSS in tailwind.config.ts:

    // tailwind.config.ts
    import type { Config } from 'tailwindcss';
    
    const config = {
      darkMode: ['class'],
      content: [
        './pages/**/*.{ts,tsx}',
        './components/**/*.{ts,tsx}',
        './app/**/*.{ts,tsx}',
        './src/**/*.{ts,tsx}',
      ],
      theme: {
        container: {
          center: true,
          padding: '2rem',
          screens: {
            '2xl': '1400px',
          },
        },
        extend: {
          colors: {
            'my-accent': 'hsl(var(--my-custom-accent))', // Map your CSS variable
            // ... existing shadcn/ui colors ...
          },
        },
      },
      plugins: [require('tailwindcss-animate')],
    } satisfies Config;
    
    export default config;
    

Now you can use bg-my-accent, text-my-accent, etc., in your Tailwind CSS classes, and they will automatically adapt to the current theme.

Advanced Styling Adjustments

Sometimes, simply changing colors isn't enough. You might need to adjust specific elements or even switch images based on the theme.

Theme-Specific Tailwind Classes

Tailwind CSS makes it easy to apply styles conditionally based on the dark class added by next-themes. Just use the dark: prefix:

<div class="bg-white text-gray-900 dark:bg-gray-800 dark:text-gray-50">
  This div changes background and text color in dark mode.
</div>
Enter fullscreen mode Exit fullscreen mode

This is useful for elements not directly tied to shadcn/ui's CSS variables, or for subtle adjustments.

Handling Theme-Specific Images or Icons

For images or SVG icons that need to change completely, you can use conditional rendering or Tailwind's dark: prefix with display utilities.

Method 1: Conditional Rendering (React)

// In a React component
'use client';
import { useTheme } from 'next-themes';
import Image from 'next/image';

export function Logo() {
  const { theme } = useTheme();
  const isDark = theme === 'dark';

  return (
    <Image
      src={isDark ? '/logo-dark.svg' : '/logo-light.svg'}
      alt="My Company Logo"
      width={100}
      height={40}
    />
  );
}
Enter fullscreen mode Exit fullscreen mode

Method 2: Tailwind CSS dark: prefix with hidden

<div>
  <img src="/logo-light.svg" alt="Light Logo" class="dark:hidden" />
  <img src="/logo-dark.svg" alt="Dark Logo" class="hidden dark:block" />
</div>
Enter fullscreen mode Exit fullscreen mode

This method renders both images but hides one based on the dark class, which can be slightly less performant but simpler for static assets.

Conclusion

Implementing light and dark mode in Next.js with shadcn/ui and Tailwind CSS is streamlined and powerful. By understanding how next-themes manages the theme state and how shadcn/ui integrates with Tailwind's dark: variants and CSS variables, you have full control over your application's appearance. This setup provides a solid foundation for creating accessible and visually appealing user interfaces that cater to individual user preferences.

FAQ

Q: Why is my theme not persisting after a page refresh?

A: Ensure your ThemeProvider from next-themes is correctly configured in your app/layout.tsx (or _app.tsx for the pages router) and wraps your entire application. The next-themes library handles persistence automatically using localStorage. If it's not working, check for JavaScript errors or ensure the ThemeProvider is mounted on the client side.

Q: How can I change the default theme from system to light or dark?

A: You can change the defaultTheme prop on your ThemeProvider component. For example, to default to light mode, set defaultTheme="light". Remember that if enableSystem is also true, the system preference will still override the defaultTheme if no explicit user choice is made. To strictly enforce a default, you might set enableSystem={false}.

Q: Can I use different fonts for light and dark modes?

A: Yes, you can! This would typically involve using CSS variables to define font families, similar to how colors are handled. You could define --font-primary-light and --font-primary-dark in your globals.css under :root and .dark selectors, respectively. Then, reference these CSS variables in your tailwind.config.ts to extend fontFamily or directly apply them in your body tag's CSS.

Top comments (0)