Implement dark mode with Next.js+TailwindCSS in 5 minutes

ยท

2 min read

Dark mode is almost a mandatory thing in web design. And, it's getting easier to implement. Let's see how we can implement this in 5 minutes with two hotcakes of frontend - Next.js & TailwindCSS.

Configure TailwindCSS

The TailwindCSS team is smart. They know about new web trends. So, they made it so easier for us to implement dark mode. In your tailwind.config.css if you add darkMode: "class", you can add dark modes classes on your elements like this -

<h1 class="text-black-100 dark:text-white">Dark mode in 5 mins</h1>

The config file will look something like this-

/** @type {import('tailwindcss').Config} */
module.exports = {
  darkMode: "class",
  content: [
    "./app/**/*.{js,ts,jsx,tsx}",
    "./pages/**/*.{js,ts,jsx,tsx}",
    "./components/**/*.{js,ts,jsx,tsx}",
    // Or if using `src` directory:
    "./src/**/*.{js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
};

Now, it will work with the user's system preference. That means it will use prefers-color-scheme feature. In short, if the user system preference has dark mode enabled then the dark: classes of TailwindCSS will work automatically.

But, I want a cool button to toggle!

Wait, buddy. We have still a couple of minutes to implement that. For that, we will use a small npm library called next-themes. It is also so easy to implement. There are two steps here. Let's go.

1. Wrap the App ๐ŸŽ

next-theme has a context provider called ThemeProvider. We have to wrap our components inside _app.js file with this Provider first. So, your _app.js file will look like this-

import "@/styles/globals.css";
import { ThemeProvider } from "next-themes";
import type { AppProps } from "next/app";

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

2. Here's your cool button to toggle ๐Ÿ”˜

Let's add a button to toggle dark and light modes. You can add this code in your index.jsx or index.tsx to test.

   <div>
      <h1 class="text-black-100 dark:text-white">Dark mode in 5 mins</h1>
      <button onClick={() => setTheme(theme === "dark" ? "light" : "dark")}>
        Cool Button
      </button>{" "}
    </div>

That's all folks.

But, what if I want to keep both the toggle button and prefers-color-scheme? The TailwindCSS team has a solution to that. You can check it here-
Supporting system preference and manual selection

If you like the article, you can Buy me a coffee โ˜•