Add Dark mode in NextJs, Tailwind CSS in just 2 min

ยท

3 min read

Dark mode is quite popular these days, almost every website, app, or operating system we use has a dark mode feature in that. iOS, macOS, Android, and Windows dark mode is everywhere. It is more likely that a user will like the website with dark mode as compared to the one without dark mode.

Now let's get started and add dark mode to our NextJs app.

Installation

1. Create Next App

With Typescript

npx create-next-app@latest dark-app --typescript --eslint
cd dark-app

With Javascript use --javascript instead of --typescript, the rest of the process will be similar for both languages.

2. Install and setup Tailwind CSS

npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p

3. Add the paths to the tailwind.config.js file

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    "./pages/**/*.{js,ts,jsx,tsx}",
    "./components/**/*.{js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}

4. Add tailwind directives to your ./styles/globals.css file

@tailwind base;
@tailwind components;
@tailwind utilities;

So we have successfully set up our Next App with Tailwind CSS, now let's start the server

npm run dev

Install Next-themes and heroicons

npm i next-themes
npm install @heroicons/react

Add theme provider in pages/_app.tsx file

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

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

set the dark mode property to class in tailwind.config.js file

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    './pages/**/*.{js,ts,jsx,tsx}',
    './components/**/*.{js,ts,jsx,tsx}',
  ],
  theme: {
    extend: {},
  },
  plugins: [],
  darkMode: 'class', // Add this property
}

Now it's time to add theme-switching functionality

import { useEffect, useState } from 'react'
import { useTheme } from 'next-themes'
import { MoonIcon, SunIcon } from '@heroicons/react/24/solid'

export default function Home() {
  // state to manage initial render
  const [mounted, setMounted] = useState(false)

  // hook to manage theme,
  // systemTheme is the current system theme,
  // theme is the current theme,
  // setTheme is the function to set the theme
  const { systemTheme, theme, setTheme } = useTheme()

  // set mounted to true after initial render
  useEffect(() => setMounted(true), [])

  // return null if component is not mounted
  if (!mounted) return null

  // if theme is set to system, use system theme else use theme
  const currentTheme = theme === 'system' ? systemTheme : theme

  return (
    <div className='h-screen bg-white dark:bg-black flex items-center justify-center'>
      <div className='flex items-center justify-center'>
        {currentTheme === 'dark' ? (
          <SunIcon
            className='h-6 w-6 cursor-pointer text-yellow-500'
            onClick={() => setTheme('light')}
          />
        ) : (
          <MoonIcon
            className='h-6 w-6 cursor-pointer text-[#F0F2F5]'
            onClick={() => {
              setTheme('dark')
            }}
          />
        )}
      </div>
    </div>
  )
}

Now we just need to add tailwind classes to get the dark mode.

For example, if you want to turn your background to black colour on dark mode add the class dark:bg-black

<div className='dark:bg-black'></div>

And boom, our NextJs app now supports dark mode, we can add different classes in the dark mode as per our needs.

Thank you for reading, I hope it helped you out!, I'll appreciate your feedback and doubts in the comments section if there are any. Happy Coding ๐Ÿš€

Wishing you all the best in further learning ๐Ÿš€

Did you find this article valuable?

Support Kunal Yadav by becoming a sponsor. Any amount is appreciated!

ย