Javascript/NextJs
Nextjs Tailwind CSS에 다크모드 적용 3분컷 방법
kimc
2023. 4. 14. 00:10
반응형
이번 글을 통해 배워갈 내용
- Tailwind CSS 사용 시 Next JS 다크모드 Next JS 라이트 모드 적용 꿀 방법
1.
next-themes 라이브러리 추가 (35kb 정도 함)
yarn add next-themes
https://www.npmjs.com/package/next-themes
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
블로그 추천 포스트
https://codemasterkimc.tistory.com/50
반응형