Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

setTheme not working #280

Closed
akshit-sharma opened this issue Mar 28, 2024 · 1 comment
Closed

setTheme not working #280

akshit-sharma opened this issue Mar 28, 2024 · 1 comment

Comments

@akshit-sharma
Copy link

akshit-sharma commented Mar 28, 2024

I am unable to set the theme using setTheme. Here's a link for minimal example.

Any pointer will be helpful.

My ThemeSwitch is a dropdown which logs the output to browser console:

// app/components/ThemeSwitch.tsx
"use client";
import { useState, useEffect } from 'react'
import { useTheme } from 'next-themes'

const ThemeSwitch = () => {
  const [ mounted, setMounted ] = useState(false)
  const { theme, setTheme, resolvedTheme } = useTheme()

  useEffect(() => {
    setMounted(true)
  }, [])

  if (!mounted) return null;

  const handleChange = (e : string) => {
    console.log(e);
    console.log('before ', theme, ' ', resolvedTheme);
    setTheme(e);
    console.log('after ', theme, ' ', resolvedTheme);
  }

  return (
    <select value={theme} onChange={e => handleChange(e.target.value)}>
      <option value="system">System</option>
      <option value="dark">Dark</option>
      <option value="light">Light</option>
    </select>
  )
}

export default ThemeSwitch

My app/layout.tsx:

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en" suppressHydrationWarning>
      <body className="bg-white dark:bg-black min-h-dvh">
        <ThemeProvider attribute="data-theme" enableSystem defaultTheme="system"
          value={{ light: 'light', dark: 'dark' }} >
          {children}
        </ThemeProvider>
      </body>
    </html>
  )
}

Output Image:

image

@akshit-sharma
Copy link
Author

It seems to work now, thanks to this comment.

Putting Providers in a separate file and importing it works.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant