Create nextjs app
Add
darkMode: "class"
to tailwind.config.css
Install next-themes
pnpm install next-themes
Create Provider.tsx file inside app directory
"use client"
import React from 'react'
import {ThemeProvider} from 'next-themes'
function Provider({
children,
}: {
children: React.ReactNode
}) {
return (
<ThemeProvider>
{children}
</ThemeProvider>
)
}
export default Provider
Add following to layout.tsx in app directory
import Provider from './Provider'
import './globals.css'
import { Inter } from 'next/font/google'
const inter = Inter({ subsets: ['latin'] })
export const metadata = {
title: 'Create Next App',
description: 'Generated by create next app',
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body className={inter.className}>
<Provider>
{children}
</Provider>
</body>
</html>
)
}
That's it now you just have use useTheme hook to switch between light and dark mode
Create ThemeToggle.tsx file
"use client"
import { useTheme } from 'next-themes'
import React, { useEffect, useState } from 'react'
function ToggleTheme() {
const [mounted, setMounted] = useState(false)
const { theme, setTheme } = useTheme()
useEffect(() => {
setMounted(true)
}, [])
if (!mounted) {
return null
}
return (
<select value={theme} onChange={e => setTheme(e.target.value)}>
<option value="system">System</option>
<option value="dark">Dark</option>
<option value="light">Light</option>
</select>
)
}
export default ToggleTheme
Top comments (0)