Spaces:
Running
Running
File size: 869 Bytes
47c0b4f |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
import React, { createContext, useState, useContext, ReactNode } from 'react'
type Theme = 'dark' | 'light'
type ThemeContextProps = {
theme: Theme
toggleTheme: () => void
}
type ThemeProviderProps = {
children: ReactNode
}
const ThemeContext = createContext<ThemeContextProps | undefined>(undefined)
export const ThemeProvider = ({ children }: ThemeProviderProps) => {
const [theme, setTheme] = useState<Theme>('dark')
const toggleTheme = () => {
setTheme((prevTheme) => (prevTheme === 'light' ? 'dark' : 'light'))
document.body.classList.toggle('light')
}
return <ThemeContext.Provider value={{ theme, toggleTheme }}>{children}</ThemeContext.Provider>
}
export const useTheme = () => {
const context = useContext(ThemeContext)
if (!context) {
throw new Error('useTheme must be used within a ThemeProvider')
}
return context
}
|