@rajace2005/theme-changer
Version:
A simple, lightweight and easy-to-use React component to add dark and light theme toggling to your application.
31 lines (24 loc) • 782 B
JavaScript
import React, { createContext, useState, useContext, useEffect } from "react";
const ThemeContext = createContext(undefined);
export const ThemeProvider = ({ children }) => {
const [theme, setTheme] = useState("light");
useEffect(() => {
document.body.classList.remove("light", "dark");
document.body.classList.add(theme);
}, [theme]);
const toggleTheme = () => {
setTheme((prevTheme) => (prevTheme === "light" ? "dark" : "light"));
};
return React.createElement(
ThemeContext.Provider,
{ value: { theme, toggleTheme } },
children
);
};
export const useTheme = () => {
const context = useContext(ThemeContext);
if (context === undefined) {
throw new Error("useTheme must be used within a ThemeProvider");
}
return context;
};