Back to overview

Easy way to use Dark Mode in Next.js + Tailwind

| 2 min read

Yesterday I was working on my personal website, and I really wanted to add a dark mode toggle. I already converted my site to use Tailwind before, so how do I enable dark mode now?

It’s simple: in Tailwind v2 dark mode is built in (https://tailwindcss.com/docs/dark-mode).

To be able to toggle the dark mode, you should put darkMode: 'class' in your tailwind.config.js. This configuration implies that a class called dark will be added to the <html> tag. Once this class is active, your dark:{class} classes will become active.

To link this functionality up with Next.js I used the lightweight next-themes library (https://github.com/pacocoursey/next-themes).

After installing this library, simply change your _app.js to include the ThemeProvider:

import { ThemeProvider } from 'next-themes';

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

export default MyApp;

Including the attribute="class" is very important, since this tells the library to use the Tailwind dark theme class.

For the toggle button I used the following:

import { useTheme } from 'next-themes';

const { theme, setTheme } = useTheme();

return (
  <button
    aria-label="Toggle Dark Mode"
    type="button"
    className="p-3 h-12 w-12 order-2 md:order-3"
    onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}
  />
);

An example of the dark:{class} code, this will use a purple background color for light mode and a darkgrey color for dark mode:

return <nav className="fixed bg-purple dark:bg-darkgrey h-16 w-full z-50" />;

And that’s it! The theme is being switched when you click the button. Live example can be found here: https://www.thomasledoux.be/ Github source: https://github.com/thomasledoux1/website-thomas Inspired by: https://leerob.io

Did you like this post? Check out my latest blog posts:

Maven on EC2
28 Jul 2023

Installing Maven on Ec2 Instance

  • aws
  • maven
  • cloud
Complete CICD Pipeline Java with Jenkins, Nexus, Sonar and AWS services
27 Jul 2023

From Code to Deployment - A Complete CICD journey for Java Apps using Jenkins, Nexus, Sonarqube, AWS ECR & ECS

  • devops
  • aws
  • cicd
Person typing on a laptop
21 Jul 2023

🏗️How to Make Animated ✨GIFs✨ For Amazon Web Services (AWS) Architectures:🏗️ A Step-by-Step Tutorial🏗️

  • aws
  • powerpoint
  • infra
  • resume