New product features | The latest in technology | The weekly debugging nightmares & more!
July 25, 2023
Take my knowledge and shove it up your brain...
Every modern website now has a dark mode toggle, and users by default expect to have a dark mode option when they visit your website.
So today we're going to learn how to implement dark mode in Next js 13.
We need one package which is next-themes
you can install it by typing npm i next-themes
1- create a theme provider
In your components folder, go ahead and create Provider.tsx
file.
We'll use that provide to wrap our entire application.
Provider.tsx
1"use client";
2
3import { ThemeProvider } from "next-themes";
4
5export default function Providers({ children }: { children: React.ReactNode }) {
6 return <ThemeProvider attribute="class">{children}</ThemeProvider>;
7}
8
2- Switch Button
We need a button to switch our theme. Obviously.
Create a file named ThemeButton.tsx
in your components folder.
ThemeButton.tsx
1"use client";
2import { useEffect, useState } from "react";
3import { useTheme } from "next-themes";
4import { BsFillSunFill, BsFillMoonStarsFill } from "react-icons/bs";
5const ThemeButton = () => {
6 const { resolvedTheme, setTheme } = useTheme();
7
8 const [mounted, setMounted] = useState(false);
9 useEffect(() => setMounted(true), []);
10 if (!mounted) {
11 return null;
12 }
13 return (
14 <button
15 aria-label="Toggle Dark Mode"
16 type="button"
17 className="flex items-center justify-center rounded-lg p-2 transition-colors hover:bg-zinc-100 dark:hover:bg-zinc-700"
18 onClick={() => setTheme(resolvedTheme === "dark" ? "light" : "dark")}
19 >
20 {resolvedTheme === "dark" ? (
21 <BsFillSunFill fill="yellow" className="h-5 w-5 text-yellow-300" />
22 ) : (
23 <BsFillMoonStarsFill className="h-5 w-5 text-slate-800" />
24 )}
25 </button>
26 );
27};
28
29export default ThemeButton;
30
You'll need to install react-icons
for the sun and moon icons or use your own icons.
3- Wrap your application
Now go to your Root layout, import the Provider, and wrap your children inside it.
Layout.tsx
1import "../globals.css";
2import { Inter } from "next/font/google";
3import Providers from "../components/Provider";
4const inter = Inter({ subsets: ["latin"] });
5export default function RootLayout({
6 children,
7}: {
8 children: React.ReactNode;
9}) {
10 return (
11 <html lang="en">
12 <body className={inter.className}>
13 <Providers>{children}</Providers>
14 </body>
15 </html>
16 );
17}
18
4- Import the Switch button in your header.
Now for the last step, all you have to do is import the switch button that we created and enjoy living in the shadows.
I tried the 2 best UI libraries. Here's my experience.
Is shadcn that good? or is nextUI going to take over?
Creating notifications never been so easy
It only takes 3 lines of code to create a beautiful notification in React js
Easiest way to create popups in react
Learn how to create popups the right way