DocsDeveloper

Dark Mode Setup

Overview

In this guide, we'll learn how to set up dark mode functionality in your application using the `next-themes` library and some help from Shadcn.

Easy CLI Install

  1. Run the following command to install the required dependencies:

    jrui add themeProvider

    Note: This will override any custom styles you have in your globals.css file. Make sure to have those ready to paste back in after installing.

  2. The command below is recommended for a button that toggles light and dark mode.

    jrui add themeToggle

Component Files

components > ThemeProvider.tsx

"use client";

import * as React from "react";
import { ThemeProvider as NextThemesProvider } from "next-themes";
import { type ThemeProviderProps } from "next-themes/dist/types";

export default function ThemeProvider({ children, ...props }: ThemeProviderProps) {
  return <NextThemesProvider {...props}>{children}</NextThemesProvider>;
}

components > ThemeToggle.tsx

"use client";

import * as React from "react";
import { Moon, Sun } from "lucide-react";
import { useTheme } from "next-themes";

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

  const toggleTheme = () => {
    setTheme(theme === "light" ? "dark" : "light");
  };

  return (
    <button onClick={toggleTheme}>
      {theme === "light" ? (
        <Sun
          className=" h-11 w-11 p-[.25rem] border-gradient card-hover"
          strokeWidth={1}
        />
      ) : (
        <Moon
          className="h-11 w-11 p-[.25rem] border-gradient card-hover"
          strokeWidth={1}
        />
      )}
      <span className="sr-only">Toggle theme</span>
    </button>
  );
}
              
}

Setup in Layout

Import the `ThemeProvider` component into your layout file and wrap your {children} with it inside the body tag:

layout.tsx

 // existing imports...
import ThemeProvider from "@/components/ThemeProvider";

// existing code...

  return (
    <html lang="en">
      <body>
        <ThemeProvider
          attribute="class"
          defaultTheme="system"
          enableSystem
          disableTransitionOnChange
        >
          {children}
        </ThemeProvider>
      </body>
    </html>
  );
}

Note: You may need to restart your development server for the changes to take effect!

Adding Styles

You now have default light and dark modes with your toggle now. If you want to try styling elements based on your modes, try using tailwind. This example shows how you can set a background color based on light and dark modes.

Example.tsx

<Reveal className=" w-20 h-20 bg-slate-200 dark:bg-slate-600">
  <h2>Example</h2>
</Reveal>