Reputation: 1
I created a ThemeContext in NextJS to toggle my website theme it working properly and on initial load of the website i have the "light" class in the body class names, but the elements that I used the "dark:" in their class names are applying the dark theme instead of initial theme that is light ...
this is my ThemeButton :
const ThemeButton = () => {
const { theme, setTheme } = useTheme();
return (
<button
className="text-primary dark:bg-containerDark bg-containerLight flex justify-center items-center w-12 h-12 rounded-xl"
onClick={() => setTheme(theme === "light" ? "dark" : "light")}
>
{theme === "light" ? (
<FaMoon className="w-5 h-5" />
) : (
<PiSunDimFill className="w-5 h-5" />
)}
</button>
);
};
export default ThemeButton;
and this is the button on Load and as you see i have light class and the "dark:" is correct in classes of the button : enter image description here
this is my themeContext if you want to see :
"use client";
import React, { createContext, useContext, useEffect, useState } from "react";
type Theme = "light" | "dark";
interface ThemeContextType {
theme: Theme;
setTheme: (theme: Theme) => void;
}
const ThemeContext = createContext<ThemeContextType | undefined>({
theme: "light",
setTheme: () => {},
});
export const useTheme = (): ThemeContextType => {
const context = useContext(ThemeContext);
if (!context) {
throw new Error("useTheme must be used within a ThemeProvider");
}
return context;
};
export const ThemeProvider = ({ children }: { children: React.ReactNode }) => {
const [theme, setTheme] = useState<Theme>("light");
// Update the body class when theme changes
useEffect(() => {
document.body.classList.remove("light", "dark");
document.body.classList.add(theme);
}, [theme]);
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
);
};
Upvotes: 0
Views: 165
Reputation: 111
Currently, seems like the dark:-
classes are recognizing the dark theme by the prefers-color-scheme
of your system instead of by class dark
or light
on the body.
You could try to config tailwind to manually toggle dark mode with class dark
and light
as the documentation here:
https://tailwindcss.com/docs/dark-mode#toggling-dark-mode-manually
Upvotes: 0