Dark Mode

Add dark mode in Next.js

Dark Mode
1

Install `next-theme`

npm install next-themes
2

Wrap your Component with the `ThemeProvider` component

/pages/_app.tsx
import '@assets/main.css'
import { ThemeProvider } from 'next-themes'

function MyApp({ Component, pageProps }) {
  return (
    <ThemeProvider>
      <Component {...pageProps} />
    </ThemeProvider>
  )
}

export default MyApp
3

Create and add `base.css` to your `main.css` file

main.css
@tailwind base;
@import './base.css';

@tailwind components;
@tailwind utilities;
base.css
:root {
  --primary: #ffffff;
  --secondary: #000000;
  --text-primary: #000000;
  --text-secondary: white;
}

[data-theme="dark"] {
  --primary: #000000;
  --secondary: #ffffff;
  --text-primary: white;
  --text-secondary: #000000;
}
4

Extend your tailwind config to use the css variables

tailwind.config.js
module.exports = {
  content: [
    './pages/**/*.{js,ts,jsx,tsx}',
    './components/**/*.{js,ts,jsx,tsx}',
  ],
  theme: {
    extend: {
      colors: {
        primary: 'var(--primary)',
        secondary: 'var(--secondary)',
      },
      textColor: {
        primary: 'var(--text-primary)',
        secondary: 'var(--text-secondary)',
      }
    },
  },
}
5

Try it and change the current theme with `useTheme`

index.tsx
import Head from 'next/head'
import { useTheme } from 'next-themes'

export default function Home() {
    const { theme, setTheme } = useTheme()
    return (
    <>
        <Head>
        <title>My Next.js App</title>
        <meta name="description" content="A simple Next.js app" />
        </Head>

        <main>
        <p className="text-primary">This text adapts its color depending on the dark or light mode</p>
        <button onClick={() => setTheme('light')}>Light Mode</button>
        <button onClick={() => setTheme('dark')}>Dark Mode</button>
        </main>
    </>
    )
}