Next.js
Adding dark mode to your next app.
Install next-themes
Start by installing next-themes (opens in a new tab):
npm install next-themes
Wrap your root layout
With pages/
You'll need a Custom App (opens in a new tab) to use next-themes.
pages/_app.tsx
import { ThemeProvider } from "next-themes"
function MyApp({ Component, pageProps }) {
return (
<ThemeProvider>
<Component {...pageProps} />
</ThemeProvider>
)
}
export default MyApp
With app/
You'll need to update your app/layout.jsx
to use next-themes.
app/layout.jsx
import { ThemeProvider } from "next-themes"
export default function Layout({ children }) {
return (
<html suppressHydrationWarning>
<head />
<body>
<ThemeProvider attribute="class" defaultTheme="system">
{children}
</ThemeProvider>
</body>
</html>
)
}
Note that ThemeProvider is a client component, not a server component. If you do not add
suppressHydrationWarning
to your <html>
you will get warnings because next-themes
updates that element. This property only applies one level deep, so it won't block hydration warnings on other elements.