Add a dark mode toggle with Next.js and Tailwind CSS
Dark mode reduces eye strain in low light. It can also save battery on OLED screens. This note shows how to add a theme switch with Next.js and Tailwind CSS.
Prerequisites
You must have Node.js on your machine.
Setup
- Create a Next.js app.
npx create-next-app my-app
- Install Tailwind CSS.
npm install tailwindcss
- Add the Tailwind layers to your CSS file.
@tailwind base;
@tailwind components;
@tailwind utilities;
Add the toggle
Keep the theme in React state. Default the theme to light. Change the background class when the user clicks the button.
import { useState } from "react";
export default function Home() {
const [theme, setTheme] = useState("light");
return (
<div className={theme === "light" ? "bg-white" : "bg-gray-800"}>
<h1>Theme switch</h1>
<button onClick={() => setTheme(theme === "light" ? "dark" : "light")}>
Toggle theme
</button>
</div>
);
}
Save the choice
Read the saved theme on load. Write the theme to localStorage when it changes.
import { useEffect, useState } from "react";
export default function Home() {
const [theme, setTheme] = useState("light");
useEffect(() => {
const savedTheme = localStorage.getItem("theme");
if (savedTheme) {
setTheme(savedTheme);
}
}, []);
useEffect(() => {
localStorage.setItem("theme", theme);
}, [theme]);
}
Follow the device setting
Use a media query so the page follows prefers-color-scheme when no saved choice exists.
@media (prefers-color-scheme: dark) {
body {
background-color: #1a202c;
color: #fff;
}
}
Check
Run the app. Click the button. The background must change. Reload the page. The last theme must remain.