본문 바로가기

front/next.js

[Next.js] next-themes로 Nextjs에서 간단히 다크모드 구현하기 (feat. tailwind)

728x90

1. next-themes

next-themes는 next.js에서 쉽게 다크 모드 및 기타 테마를 구현할 수 있도록 도와주는 라이브러리이다.

해당 라이브러리를 사용하면 정말 간단하게 다크 모드를 구현할 수 있다. 

 

아래 사용방법은 nextjs + tailwind에서 다크모드를 구현하는 방법이다. 

 

2. 사용방법

1) 설치

npm install next-themes
yarn add next-themes

 

npm을 통해 next-themes를 설치해 준다. 

 

 

2) tailwind css와 연동

// tailwind.config.js
module.exports = {
  darkMode: 'class', // 다크 모드를 클래스 기반으로 설정
  content: [
    './app/**/*.{js,ts,jsx,tsx}',
    './components/**/*.{js,ts,jsx,tsx}',
  ],
  theme: {
    extend: {},
  },
  plugins: [],
};

 

tailwind.config.js에 들어가서 darkMode를 추가해 준다.

 

다크모드를 사용할 때 어떤 방식을 사용할지 설정하는 부분이라고 생각하면 된다.

class와 media 두 부분으로 나뉜다.

 

예를 들어 class로 설정할 경우, <html class="dark">를 입력해 주면 다크모드가 적용된다.

media로 설정할 경우, 사용자 시스템의 다크 모드 설정에  따라 자동으로 다크모드가 적용된다. 

 

 

3) ThemeProvider 설정

// app/layout.tsx
import { ThemeProvider } from 'next-themes';
import '../styles/globals.css';

export const metadata = {
  title: 'Next.js with next-themes',
  description: 'A Next.js project with Tailwind CSS and dark mode using next-themes.',
};

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body>
        <ThemeProvider attribute="class">
          {children}
        </ThemeProvider>
      </body>
    </html>
  );
}

 

그 후 app > layout 페이지로 이동한 후, ThemeProvider를 설정해 준다.

그리고 attribute="class"를 입력해 준다. 

 

 

4) 다크모드 토글 버튼 만들기

// components/ThemeToggle.tsx
'use client';

import { useTheme } from 'next-themes';

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

  return (
    <button
      onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}
      className="p-2 bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-gray-200 rounded"
    >
      {theme === 'dark' ? 'Light Mode' : 'Dark Mode'}
    </button>
  );
};

export default ThemeToggle;

 

이제 다크모드 토글 버튼을 만들어서, 버튼을 클릭할 때마다 모드가 변경되게 바꿔준다. 

 

토글버튼을 만들 땐, next-themes 라이브러리에서 제공하는 useTheme 훅을 사용하면 된다. 

useTheme 훅은 현재 테마와 테마를 변경하는 함수를 가져온다. 

따라서 theme은 현재 테마가, setTheme는 현태 테마를 변경하는 함수가 된다. 

 

 

 

완료되면 위 화면처럼 다크모드가 구현된다. 

 

 

 

https://github.com/pacocoursey/next-themes

 

GitHub - pacocoursey/next-themes: Perfect Next.js dark mode in 2 lines of code. Support System preference and any other theme wi

Perfect Next.js dark mode in 2 lines of code. Support System preference and any other theme with no flashing - pacocoursey/next-themes

github.com

 

728x90