How to enable dark mode in Nextjs and Tailwind CSS?

Nextjs + Tailwind CSS

How to enable dark mode in Nextjs and Tailwind CSS?

Enabling light and dark modes with Nextjs, tailwind css, radix-ui, and flowbite

Rajdeep singh
FrontEnd web
Published in
4 min readMar 11

--

Now a day, Enabling light and dark themes is an important phase in frontend development. Especially you and your teammate use tailwind css with nextjs, then enable the theme toggle functionality. It takes only 5 to 10 mint.

I teach you how to enable dark and light modes and toggle functionality with copy-paste on code. Whatever library you use, for example, radix UI or flowbite, The process is the same with tailwind css and nextjs.

All the code is available on GitHub, and check out the live site demo.

Steps

  1. Create a fresh project with nextjs, tailwind css
  2. Enable dark mode in tailwind CSS
  3. Install next-themes package
  4. Config the next-themes
  5. How to use the next-themes package with nextjs?
  6. Conclusion

Create a fresh project with nextjs, tailwind css

The first step is to create a new nextjs project with create-next-app

npx create-next-app@latest

# or

yarn create next-app

# or

pnpm create next-app

Then you install the tailwind css in the nextjs project and config it.

npm install -D tailwindcss postcss autoprefixer

# or

yarn add -D tailwindcss postcss autoprefixer

# or

pnpm add -D tailwindcss postcss autoprefixer

For configuration, the tailwind css to runs the following command. following the command, generate two files tailwind.config.js and postcss.config.js.

npx tailwindcss init -p

After both files are generated, now Add the template paths in your tailwind.config.js file.

// tailwind.config.js

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

// Or if using `src` directory:
"./src/**/*.{js,ts,jsx,tsx}",
],
theme: {
extend: {},
},
plugins: [],
}

Adding the Tailwind directives to your global CSS file.

// globals.css

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

Now you have successfully created a new nextjs project and configured the tailwind css; check everything is fine, then run the npm run dev command.

Enable dark mode in tailwind CSS

The next step is To enable dark mode functionality in tailwind css. You need to add one more line darkMode:"class” to the tailwind.config.js file.

/** @type {import('tailwindcss').Config} */
module.exports = {

darkMode: 'class',

content: [
"./pages/**/*.{js,ts,jsx,tsx}",
"./components/**/*.{js,ts,jsx,tsx}",
],
theme: {
extend: {},
},
plugins: [],
}

Install next-themes package

The next phase is to install or add a next-themes package to your project.

npm install -D next-themes
# or

yarn add -D next-themes

# or

pnpm add -D next-themes

Config the next-themes

After installation is complete and now we config the next-themes package with nextjs. The next-themes package provides a themeProvide component to wrap our Layout and Component with themeProvide in _app.tsx file.

TypeScript

// _app.tsx

import '@/styles/globals.css'
import type { AppProps } from 'next/app'

import { ThemeProvider } from 'next-themes'

import Layout from "@/components/Layout";

export default function App({ Component, pageProps }: AppProps) {

return( <ThemeProvider
attribute="class" >
<Layout>
<Component {...pageProps} />
</Layout>
</ThemeProvider>
)

}

JavaScript

// _app.jsx

import '../styles/globals.css'

import { ThemeProvider } from 'next-themes'

import Layout from "../components/Layout";

export default function App({ Component, pageProps }) {

return( <ThemeProvider
attribute="class" >
<Layout>
<Component {...pageProps} />
</Layout>
</ThemeProvider>
)

}

The next-themes package has a small and easily read documentation; please look at the next-thems docs before starting.

How to use the next-themes package with nextjs?

After the installation and configuration step is complete, the next step uses the next-themes package.

The next-themes packages provide a useTheme hook. With the help of a hook, we easily change or toggle the theme from light to dark with one click.

import { FaFacebook, FaTwitter, FaLinkedin, FaInstagram, FaSearch, FaSun, FaRegMoon } from "react-icons/fa";
import { useTheme } from 'next-themes'

function Header() {
const { theme, setTheme } = useTheme()

return (
<header className="bg-white px-2 sm:px-4 py-2.5 dark:bg-gray-900 w-full">

<div className="container flex flex-wrap items-center justify-between mx-auto">

<a href="/" className="flex items-center">
<span className="self-center text-xl font-semibold whitespace-nowrap dark:text-white">OpenBlog</span>
</a>

<div className="flex md:order-2">

<ul className="flex flex-row p-4 md:space-x-8 md:mt-0 md:text-sm md:font-medium">

<li>

<button className="block py-2 pl-3 pr-4 rounded md:p-0" onClick={()=> setTheme( theme === "dark"? "light": "dark" )}>
{ theme==="dark"? <FaSun/>: <FaRegMoon/> }
</button>

</li>

</ul>

</div>

</div>

</header>
)

}

export default Header

The useTheme hook provides a theme and setTheme function.

const { theme, setTheme } = useTheme()

Now, We add an onClick event on the button, and our onClick event looks like this () => setTheme(theme==="dark"?"light":"dark") . When somebody clicks the button, the setTheme function triggers, changing the theme.

<button className="block py-2 pl-3 pr-4 rounded md:p-0" onClick={()=> setTheme( theme === "dark"? "light": "dark" )}>

{ theme === "dark" ? <FaSun/>: <FaRegMoon/> }

</button>

You can show icons based on a theme; if you enable a dark theme, you can show a Sun icon; if you the light theme, you show a moon icon.

theme === "dark" ? <FaSun/>: <FaRegMoon/> 

Note

For icons, I installed one more extra package called react-icons. it help you to use open source SVG icons with download.

Conclusion

Enabling the theme toggle with next-themes, tailwind CSS and nextjs is easy, and we do not need to write 100-line code with javascript to enable the theme toggle with nextjs.

You do not need to write a javascript to target the dom manually, and enabling the theme toggle with the next-themes package works like a copy-paste of code.

You can share and follow us on Twitter and Linkedin. If you like my work, please read more content on the officialrajdeepsingh.dev, Nextjs, frontend web, and Sign up for a free newsletter.

You can also check out awesome-next, a curated list of awesome Nextjs-based libraries that help build small and large-scale applications with next.js.

--

--

Rajdeep singh
FrontEnd web

JavaScript || Reactjs || Nextjs || Python || Rust || Biotechnology || Bioinformatic || Front-end Developer || Author https://officialrajdeepsingh.dev/