-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththeme-toggle.tsx
42 lines (34 loc) · 1006 Bytes
/
theme-toggle.tsx
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
34
35
36
37
38
39
40
41
42
'use client'
import Cookie from 'js-cookie'
import React from 'react'
import styles from '../page.module.scss'
export const ThemeToggle = ({ initialTheme }: { initialTheme: string }) => {
const [theme, setTheme] = React.useState(initialTheme)
React.useEffect(() => {
if (initialTheme === 'system') {
setTheme(
document.documentElement.getAttribute('data-theme-color') || 'light'
)
}
}, [initialTheme])
function handleClick() {
// get next theme
const newTheme = theme === 'light' ? 'dark' : 'light'
// set theme for local state
setTheme(newTheme)
// set cookies for next visit
Cookie.set('theme-color', newTheme, {
expires: 1000,
})
// set theme for html
document.documentElement.setAttribute('data-theme-color', newTheme)
}
if (theme === 'system') {
return <button className={styles.toggle}>Loading</button>
}
return (
<button onClick={handleClick} className={styles.toggle}>
Switch to {theme === 'light' ? 'dark' : 'light'} mode
</button>
)
}