nextjs dark mode with tailwind css example

In this section we will see how to use dark mode in nextjs with tailwind css using next-themes library. next-themes is perfect Next.js dark mode in 2 lines of code. Support System preference and any other theme with no flashing.


Tool Use

NextJS

Tailwind CSS 3.v

next-themes


First you need to setup NextJS project with tailwind css. You can install manually or you read below blog.

Install Tailwind CSS In Next JS with Typescript

How to Install & Setup Tailwind CSS v3 In NextJS


Install next-themes for dark mode

Run below command to install next-themes.

npm install next-themes
# or
yarn add next-themes


Add dark mode class in tailwind.config.js

tailwind.config.js

module.exports = {
  darkMode: 'class',
  content: [
    "./pages/**/*.{js,jsx,ts,tsx}",
    "./components/**/*.{js,jsx,ts,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
};


Now, you need to import them in pages/_app.tsx or _app.js.

pages/_app.tsx or _app.js

import { ThemeProvider } from 'next-themes'

function MyApp({ Component, pageProps }) {
 return (
  <ThemeProvider attribute='class'>
   <Component {...pageProps} />
  </ThemeProvider>
 )
}

export default MyApp


Now import useTheme and use dark mode toggle switch.

pages/index.js or pages/index.tsx

import Head from "next/head";
import React from "react";
import { useTheme } from 'next-themes'

export default function Home() {
  const { theme, setTheme } = useTheme()
  return (
    <div>
      <Head>
        <title>Next App Dark Mode With Tailwind CSS</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <div className="flex flex-col items-center justify-center h-screen bg-white dark:bg-black">
        <button
          onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}
          className="px-4 py-2 text-white bg-black rounded dark:bg-white dark:text-black">
          Dark Toggle
        </button>
        <div className="mt-6">
          <div
            className="max-w-sm p-6 bg-white border border-gray-200 rounded-lg shadow-md hover:bg-gray-100 dark:bg-gray-800 dark:border-gray-700 dark:hover:bg-gray-700"
          >
            <h5 className="mb-2 text-2xl font-bold tracking-tight text-gray-900 dark:text-white">
              NextJS dark Mode With Tailwind CSS
            </h5>
            <p className="font-normal text-gray-700 dark:text-gray-400">
              install & setup nextjs dark mode using tailwind css 3
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}


Nextjs before dark mode toggle button.

nextjs light mode toggle switch with tailwind css


After click dark mode toggle button.

nextjs dark mode toggle switch with tailwind css


Run server

npm run dev


Read Also

Create Responsive Navbar Menu in Next js with Tailwind CSS