Tailwind CSS Dark Mode with Next.js

Today I learned how to implement a clean dark mode solution using Tailwind CSS in a Next.js application.

Implementation Steps

  1. Configure Tailwind:
// tailwind.config.js
module.exports = {
  darkMode: 'class',
  // ...
}
  1. Add dark mode toggle:
const [darkMode, setDarkMode] = useState(false)
 
useEffect(() => {
  document.documentElement.classList.toggle('dark', darkMode)
}, [darkMode])
  1. Use in components:
<div className="bg-white text-black dark:bg-neutral-900 dark:text-white">
  Content
</div>

Key Takeaways

  • Use 'class' strategy for more control
  • Persist preference in localStorage
  • Add transition classes for smooth switching
  • Consider using next-themes package for SSR support

This approach provides a seamless dark mode experience with minimal configuration.