Full Stack Personal Blog 04: Dark Mode
cz2025.05.26 08:19

Shadcn/ui is a modern React UI component library designed to provide customizable, high-quality, dependency-free UI components. Leveraging the flexibility of Tailwind CSS and React, it offers a set of easy-to-use, responsive, and extensible UI components that help developers quickly build beautiful and feature-rich application interfaces, while maintaining design consistency and flexibility.

1. Configure Dark Mode

  • Refer to the official documentation and use next-themes to configure dark mode: https://ui.shadcn.com/docs/dark-mode/next
  • The principle is to add the dark class to the html element when switching to dark mode, and then adjust styles via CSS variables such as --foreground, --background, etc.

2. Switch Modes

  • Use the useTheme hook provided by next-themes to get the current theme and switch themes
// src/components/ThemeModeToggle.tsx
'use client'

import { Moon, Sun } from 'lucide-react'
import { useTheme } from 'next-themes'

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

  return (
    <div
      className="hover:bg-accent hover:text-accent-foreground text-foreground relative flex size-8 cursor-pointer items-center justify-center transition-colors"
      onClick={() => (theme === 'light' ? setTheme('dark') : setTheme('light'))}
    >
      <Sun className="size-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0" />
      <Moon className="absolute left-1/2 top-1/2 size-4 -translate-x-1/2 -translate-y-1/2 rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100" />
    </div>
  )
}

Comments