Javascript/NextJs

Nextjs Tailwind CSS에 다크모드 적용 3분컷 방법

kimc 2023. 4. 14. 00:10
반응형

 


 

 

이번 글을 통해 배워갈 내용

  1. Tailwind CSS 사용 시 Next JS 다크모드 Next JS 라이트 모드 적용 꿀 방법

 

1.

next-themes 라이브러리 추가 (35kb 정도 함)

yarn add next-themes

https://www.npmjs.com/package/next-themes

 

next-themes

An abstraction for themes in your Next.js app.. Latest version: 0.2.1, last published: 7 months ago. Start using next-themes in your project by running `npm i next-themes`. There are 141 other projects in the npm registry using next-themes.

www.npmjs.com

 

2.

tailwind.config.js 에 darkMode:class, 추가

const { fontFamily } = require('tailwindcss/defaultTheme');


module.exports = {
...
	darkMode: 'class',
...
};

 

3.

_app.ts 에 ThemeProvider 추가

import { ThemeProvider } from 'next-themes';

export default function App({ Component, pageProps }: AppProps) {
  return (
      <ThemeProvider attribute="class">
        <Component {...pageProps} />
      </ThemeProvider>
  );

 

4.

코드에 적용

export default function Home() {
  const { systemTheme, theme, setTheme } = useTheme();
  const currentTheme = theme === 'system' ? systemTheme : theme;

  const toggleDarkMode = () => {
    if (theme == 'dark') {
      setTheme('light');
    } else {
      setTheme('dark');
    }
  };
    return (
    <main className="dark:bg-darkBlue dark:text-white">

		<div onClick={toggleDarkMode}>
            <div className={`${theme == 'dark' ? 'hidden' : ''} w-5 h-5`} >
            	라이트
            </div>
            
            <div className={`${theme == 'dark' ? '' : 'hidden'} w-5 h-5`}>
            	다크
            </div>
		</div>
    </main>
    )
}

 

 


참조 및 인용

https://tailwindcss.com/docs/dark-mode

 

Dark Mode - Tailwind CSS

Using Tailwind CSS to style your site in dark mode.

tailwindcss.com

 

 

 


블로그 추천 포스트

https://codemasterkimc.tistory.com/50

 

300년차 개발자의 좋은 코드 5계명 (Clean Code)

이번 글을 통해 배워갈 내용  좋은 코드(Clean Code)를 작성하기 위해 개발자로서 생각해볼 5가지 요소를 알아보겠습니다. 개요 좋은 코드란 무엇일까요? 저는 자원이 한정적인 컴퓨터 세상에서 좋

codemasterkimc.tistory.com

 


 

반응형