Skip to content

Commit 9a98533

Browse files
authored
fix: ensure site syncs with system theme changes (#49)
* fix: tweaking theme provider * formatting changes * chore: disable eslint warning and update setter name --------- Resolves #48 Co-authored-by: satnaing <satnaingdev@gmail.com>
1 parent c5d163d commit 9a98533

File tree

1 file changed

+23
-15
lines changed

1 file changed

+23
-15
lines changed

src/components/theme-provider.tsx

+23-15
Original file line numberDiff line numberDiff line change
@@ -26,34 +26,42 @@ export function ThemeProvider({
2626
storageKey = 'vite-ui-theme',
2727
...props
2828
}: ThemeProviderProps) {
29-
const [theme, setTheme] = useState<Theme>(
29+
const [theme, _setTheme] = useState<Theme>(
3030
() => (localStorage.getItem(storageKey) as Theme) || defaultTheme
3131
)
3232

3333
useEffect(() => {
3434
const root = window.document.documentElement
35+
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
3536

36-
root.classList.remove('light', 'dark')
37-
38-
if (theme === 'system') {
39-
const systemTheme = window.matchMedia('(prefers-color-scheme: dark)')
40-
.matches
41-
? 'dark'
42-
: 'light'
37+
const applyTheme = (theme: Theme) => {
38+
root.classList.remove('light', 'dark') // Remove existing theme classes
39+
const systemTheme = mediaQuery.matches ? 'dark' : 'light'
40+
const effectiveTheme = theme === 'system' ? systemTheme : theme
41+
root.classList.add(effectiveTheme) // Add the new theme class
42+
}
4343

44-
root.classList.add(systemTheme)
45-
return
44+
const handleChange = () => {
45+
if (theme === 'system') {
46+
applyTheme('system')
47+
}
4648
}
4749

48-
root.classList.add(theme)
50+
applyTheme(theme)
51+
52+
mediaQuery.addEventListener('change', handleChange)
53+
54+
return () => mediaQuery.removeEventListener('change', handleChange)
4955
}, [theme])
5056

57+
const setTheme = (theme: Theme) => {
58+
localStorage.setItem(storageKey, theme)
59+
_setTheme(theme)
60+
}
61+
5162
const value = {
5263
theme,
53-
setTheme: (theme: Theme) => {
54-
localStorage.setItem(storageKey, theme)
55-
setTheme(theme)
56-
},
64+
setTheme,
5765
}
5866

5967
return (

0 commit comments

Comments
 (0)