DEV Community

Cover image for How to use tailwindcss to add dark mode to your website?
Hardique Dasore
Hardique Dasore

Posted on

How to use tailwindcss to add dark mode to your website?

Dark mode has become a popular feature in recent years, as it allows users to reduce eye strain and conserve battery life on their devices. In this blog post, we will show you how to toggle between dark and light mode on your website using Next.js and Tailwind CSS.

First, let's set up a basic Next.js project. Create a new directory and run the following command to initialize a Next.js project:

npx create-next-app
Enter fullscreen mode Exit fullscreen mode

Next, we need to install Tailwind CSS. Run the following command in your project directory:

npm install tailwindcss
npx tailwindcss init
Enter fullscreen mode Exit fullscreen mode

In your tailwind.config.js file, you will need to add the following line to enable the darkModeclass:

module.exports = {
  theme: {
    extend: {},
  },
  variants: {},
  plugins: [],
  dark: 'class',
};
Enter fullscreen mode Exit fullscreen mode

Now in App.js add the following piece of code:

import React, { useEffect, useState } from "react";

// Function to toggle modes between dark and light 
// This can be moved into a separate js file in order to share it between pages
function useDarkMode() {
  const [theme, setTheme] = useState(
    typeof window !== "undefined" ? localStorage.theme : "dark"
  );
  const colorTheme = theme === "dark" ? "light" : "dark";

  useEffect(() => {
    const root = window.document.documentElement;

    root.classList.remove(colorTheme);
    root.classList.add(theme);

    if (typeof window !== "undefined") {
      localStorage.setItem("theme", theme);
    }
  }, [theme]);

  return [colorTheme, setTheme];
}

function App() {
  const [colorTheme, setTheme] = useDarkMode();

  return (
    <div className="dark:bg-zinc-900 bg-white h-screen dark:text-black text-white place-items-center grid">
      <button className={`bg-gray-500 ${colorTheme !=='dark'?'hover:bg-yellow-400':' hover:bg-blue-400'} text-white p-2 rounded-full`} onClick={() => setTheme(colorTheme !== "dark"? "light": "dark")}>
//HeroIcons is used for svg vectors
        {colorTheme === 'dark' ? <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-6 h-6">
          <path strokeLinecap="round" strokeLinejoin="round" d="M21.752 15.002A9.718 9.718 0 0118 15.75c-5.385 0-9.75-4.365-9.75-9.75 0-1.33.266-2.597.748-3.752A9.753 9.753 0 003 11.25C3 16.635 7.365 21 12.75 21a9.753 9.753 0 009.002-5.998z" />
        </svg> : <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-6 h-6">
          <path strokeLinecap="round" strokeLinejoin="round" d="M12 3v2.25m6.364.386l-1.591 1.591M21 12h-2.25m-.386 6.364l-1.591-1.591M12 18.75V21m-4.773-4.227l-1.591 1.591M5.25 12H3m4.227-4.773L5.636 5.636M15.75 12a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0z" />
        </svg>}

      </button>
    </div>

  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

We can also create a separate component for the toggle button but for demo purposes, we have added the piece of code to App.js file.

This code uses the useState and useEffect hooks to keep track of the dark/light mode state and sets the background color of the page based on the state. The button toggles the mode state when clicked.

That's it! With just a few lines of code, you can add a dark mode toggle to your Next.js website using Tailwind CSS. Users will appreciate the ability to switch between dark and light modes to reduce eye strain and save battery life on their devices.

Code Snippet: GitHub: Tailwindcss Dark Mode

Happy Coding!

Top comments (0)