Dark Mode (다크 모드)
HeroUI v3에 라이트, 다크, 시스템 테마 전환을 추가하는 방법을 안내해요. 해요체로 쉽게 설명드릴게요.
출처: HeroUI Dark Mode
본문
HeroUI 다크 모드는 CSS 기반이에요. 컴포넌트는 루트 요소에서 테마 변수를 읽기 때문에 HeroUI 프로바이더가 필요하지 않아요. <html>에 dark 클래스나 data-theme="dark"를 추가하면 HeroUI가 다크 테마를 적용해요.
<html class="dark" data-theme="dark">
<body class="bg-background text-foreground">
<!-- Your app -->
</body>
</html>
앱 셸에 bg-background와 text-foreground 클래스를 유지해서 페이지 배경이 활성 테마에 따라 바뀌도록 해요.
HeroUI의 내장 라이트/다크 테마는
.light/.dark클래스와data-theme="light"/data-theme="dark"속성 모두에 응답해요. 둘 다 수동으로 설정한다면 값이 일치하도록 유지해요.
Next.js에서 next-themes 사용
Next.js 앱에서 테마 유지, 시스템 환경설정 지원, 하이드레이션 전 깜빡임 없는 동작이 필요하다면 next-themes를 사용해요.
next-themes 설치
npm i next-themes
pnpm add next-themes
yarn add next-themes
bun add next-themes
App Router
next-themes용 클라이언트 프로바이더를 만들어요.
// app/providers.tsx
"use client";
import {ThemeProvider as NextThemesProvider} from "next-themes";
export function Providers({children}: {children: React.ReactNode}) {
return (
<NextThemesProvider
attribute="class"
defaultTheme="system"
enableSystem
disableTransitionOnChange
>
{children}
</NextThemesProvider>
);
}
루트 레이아웃에서 앱을 프로바이더로 감싸요. next-themes가 하이드레이션 전에 <html> 요소를 업데이트하므로 <html>에 suppressHydrationWarning을 추가해요.
// app/layout.tsx
import "./globals.css";
import {Providers} from "./providers";
export default function RootLayout({children}: {children: React.ReactNode}) {
return (
<html lang="en" suppressHydrationWarning>
<body className="bg-background text-foreground">
<Providers>{children}</Providers>
</body>
</html>
);
}
테마 스위처 (Theme switcher)
클라이언트 컴포넌트 안에서 next-themes의 useTheme을 사용해요. 활성 테마는 SSR 중에 알 수 없으므로 마운트될 때까지 렌더링을 지연해요.
// app/components/theme-switcher.tsx
"use client";
import {Button} from "@heroui/react";
import {useTheme} from "next-themes";
import {useEffect, useState} from "react";
export function ThemeSwitcher() {
const [mounted, setMounted] = useState(false);
const {resolvedTheme, setTheme, theme} = useTheme();
useEffect(() => {
setMounted(true);
}, []);
if (!mounted) return null;
const activeTheme = theme === "system" ? resolvedTheme : theme;
return (
<div className="flex items-center gap-2">
<Button
variant={activeTheme === "light" ? "primary" : "secondary"}
onPress={() => setTheme("light")}
>
Light
</Button>
<Button
variant={activeTheme === "dark" ? "primary" : "secondary"}
onPress={() => setTheme("dark")}
>
Dark
</Button>
<Button variant={theme === "system" ? "primary" : "secondary"} onPress={() => setTheme("system")}>
System
</Button>
</div>
);
}
Pages Router
pages/의 경우 pages/_app.tsx에서 애플리케이션을 감싸요.
// pages/_app.tsx
import "@/styles/globals.css";
import type {AppProps} from "next/app";
import {ThemeProvider as NextThemesProvider} from "next-themes";
export default function App({Component, pageProps}: AppProps) {
return (
<NextThemesProvider
attribute="class"
defaultTheme="system"
enableSystem
disableTransitionOnChange
>
<Component {...pageProps} />
</NextThemesProvider>
);
}
커스텀 테마 이름 사용 (Using custom theme names)
attribute="class" 설정은 내장 light와 dark 테마에 잘 맞아요. 커스텀 테마 CSS가 data-theme 선택자로 작성되어 있다면 next-themes가 data-theme을 쓰도록 설정해요.
<NextThemesProvider
attribute="data-theme"
defaultTheme="system"
enableSystem
themes={["light", "dark", "ocean", "ocean-dark"]}
>
{children}
</NextThemesProvider>
커스텀 themes 목록을 넘길 때 내장 테마를 계속 사용하려면 "light"와 "dark"를 포함해요.
React에서 useTheme 사용
Vite나 Create React App 같은 순수 React 앱을 만들고 next-themes가 필요 없다면 HeroUI의 useTheme 훅을 사용해요.
이 훅은 @heroui/react에서 내보내져요. 선택한 테마를 localStorage에 저장하고, "system"을 사용자의 OS 환경설정에서 결정하며, <html>에 class와 data-theme 속성을 모두 적용해요.
// src/components/theme-switcher.tsx
import {Button, useTheme} from "@heroui/react";
export function ThemeSwitcher() {
const {resolvedTheme, setTheme, theme} = useTheme("system");
return (
<div className="flex items-center gap-2">
<Button
variant={resolvedTheme === "light" ? "primary" : "secondary"}
onPress={() => setTheme("light")}
>
Light
</Button>
<Button
variant={resolvedTheme === "dark" ? "primary" : "secondary"}
onPress={() => setTheme("dark")}
>
Dark
</Button>
<Button variant={theme === "system" ? "primary" : "secondary"} onPress={() => setTheme("system")}>
System
</Button>
</div>
);
}
앱마다 하나의 테마 컨트롤러를 사용해요. Next.js에서는
next-themes와 그useTheme훅을 선호해요. 순수 React 앱에서는@heroui/react의useTheme을 사용해요.
두 테마 모두 스타일링 (Styling for both themes)
테마 인지 유틸리티는 CSS 변수를 읽기 때문에 자동으로 동작해요:
<main className="min-h-screen bg-background text-foreground">
<section className="bg-surface text-surface-foreground shadow-surface">
Theme-aware content
</section>
</main>
다크 모드에서만 적용되는 일회성 변경에는 dark: 변형을 사용해요:
<div className="bg-background text-foreground dark:border-default">
Custom dark-mode adjustment
</div>
더 알아보기 (Learn more)
- next-themes - Next.js 테마 라이브러리
- Tailwind CSS 다크 모드 -
dark:변형