first
This commit is contained in:
@@ -0,0 +1,45 @@
|
||||
import { createContext, useContext, useEffect, useState } from 'react';
|
||||
|
||||
const initialState = {
|
||||
theme: 'light',
|
||||
setTheme: (theme: string) => {
|
||||
theme;
|
||||
return null;
|
||||
},
|
||||
};
|
||||
|
||||
type ThemeProviderProps = { children: React.ReactNode; defaultTheme?: string; storageKey?: string };
|
||||
|
||||
const ThemeProviderContext = createContext(initialState);
|
||||
|
||||
export function ThemeProvider(props: ThemeProviderProps) {
|
||||
const { children, defaultTheme = 'light', storageKey = 'theme' } = props;
|
||||
const [theme, setTheme] = useState(() => localStorage.getItem(storageKey) || defaultTheme);
|
||||
|
||||
useEffect(() => {
|
||||
const root = window.document.documentElement;
|
||||
|
||||
root.classList.remove('light', 'dark');
|
||||
|
||||
root.classList.add(theme);
|
||||
}, [theme]);
|
||||
|
||||
const value = {
|
||||
theme,
|
||||
setTheme: (newTheme: string) => {
|
||||
localStorage.setItem(storageKey, newTheme);
|
||||
setTheme(newTheme);
|
||||
return null;
|
||||
},
|
||||
};
|
||||
|
||||
return <ThemeProviderContext.Provider value={value}>{children}</ThemeProviderContext.Provider>;
|
||||
}
|
||||
|
||||
export const useTheme = () => {
|
||||
const context = useContext(ThemeProviderContext);
|
||||
|
||||
if (context === undefined) throw new Error('useTheme must be used within a ThemeProvider');
|
||||
|
||||
return context;
|
||||
};
|
||||
Reference in New Issue
Block a user