Tailwind v4와 next-themes를 활용한 다크 모드
발행: (2026년 1월 11일 오전 04:10 GMT+9)
3 min read
원문: Dev.to
Source: Dev.to
Installation
npm install next-themes
Setup in main.jsx
import { ThemeProvider } from "next-themes";
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
createRoot(document.getElementById("root")).render(
);
Provider Props
| Prop | Description |
|---|---|
attribute="class" | dark 클래스를 “ 요소에 추가합니다 |
defaultTheme="system" | 기본값으로 시스템 환경설정을 사용합니다 |
enableSystem | 시스템 테마를 자동으로 감지합니다 |
storageKey="theme-name" | (Optional) 사용자 정의 localStorage 키 |
Tailwind CSS Configuration
@import "tailwindcss";
/* Enable dark variant */
@variant dark (&:is(.dark *));
/* Define custom color tokens */
@theme {
--color-primary: light-dark(#10b981, #dc2626);
--color-surface: light-dark(#f8fafc, #0f172a);
}
Syntax for color tokens
--color-[name]: light-dark([light-color], [dark-color]);
Example
--color-primary: light-dark(#10b981, #dc2626);
Using the Tokens in JSX
Hello
Content
Note: 변수 이름에
text-또는bg-를 포함하지 마세요; Tailwind가 해당 접두사를 자동으로 추가합니다.
Theme Toggle Component
import { useTheme } from "next-themes";
import { useEffect, useState } from "react";
function ThemeToggle() {
const { theme, setTheme } = useTheme();
const [mounted, setMounted] = useState(false);
// Prevent mismatched SSR rendering
useEffect(() => setMounted(true), []);
if (!mounted) return null;
return (
setTheme(theme === "dark" ? "light" : "dark")}>
Toggle Theme
);
}
A minimal version without the mount guard:
import { useTheme } from "next-themes";
function ThemeToggle() {
const { theme, setTheme } = useTheme();
return (
setTheme(theme === "dark" ? "light" : "dark")}>
{theme === "dark" ? "🌙" : "☀️"}
);
}
useTheme API Reference
const { theme, setTheme, systemTheme, themes } = useTheme();
| Property | Type | Description |
|---|---|---|
theme | string | 현재 테마: "light", "dark", 또는 "system" |
setTheme(name) | function | 테마를 변경합니다 |
systemTheme | string | 시스템 환경설정: "light" 또는 "dark" |
themes | array | 사용 가능한 테마 목록 |
Extended Color Tokens
@theme {
/* Backgrounds */
--color-surface: light-dark(#f8fafc, #0f172a);
--color-card: light-dark(#ffffff, #1e293b);
/* Text */
--color-primary: light-dark(#1f2937, #f9fafb);
--color-secondary: light-dark(#6b7280, #9ca3af);
/* Brand */
--color-brand: light-dark(#10b981, #34d399);
--color-accent: light-dark(#3b82f6, #60a5fa);
}
Troubleshooting
-
Dark mode not activating
- DevTools에서 “ 가 나타나는지 확인하세요.
localStorage를 비우고 페이지를 새로 고칩니다.- 컴파일된 CSS에
@variant dark (&:is(.dark *));규칙이 포함되어 있는지 확인하세요.
-
Colors not changing
- 사용자 정의 색상 변수 이름에
text-또는bg-를 포함하지 마세요. - 올바른
light-dark구문을 사용하세요. 예:light-dark(#fff, #000).
- 사용자 정의 색상 변수 이름에
Quick Reference
// Setup
// Toggle theme
const { theme, setTheme } = useTheme();
setTheme(theme === "dark" ? "light" : "dark");
// Define colors
--color-primary: light-dark(#10b981, #dc2626);
// Use colors
…
Links