DEV Community

Ankit Sahu
Ankit Sahu

Posted on

Switching Between Dark and Light in Nextjs13.4 App

Create nextjs app

Create nextjs app

Add darkMode: "class" to tailwind.config.css

Image description

Install next-themes

pnpm install next-themes
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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>
  )
}

Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Top comments (0)