summaryrefslogtreecommitdiffstats
path: root/components/ThemeSwitcher/index.tsx
blob: f6f6a68d6206d55d43568f1f928eb8d0ad596a8f (plain)
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
import React from 'react';
import classes from './theme-switcher.module.css';

export function ThemeSwitcher() {
  const [theme, setTheme] = React.useState('dark');

  React.useEffect(() => {
    const SITE_THEME = window.localStorage.getItem('site_theme');

    if (SITE_THEME) {
      setTheme(SITE_THEME);
    } else {
      setTheme('dark');
      window.localStorage.setItem('site_theme', 'dark');
    }
  }, []);

  React.useEffect(() => {
    const root = document.querySelector('html');
    root?.setAttribute('data-theme', theme);
    window.localStorage.setItem('site_theme', theme);
  }, [theme]);

  return (
    <div className={classes.wrapper}>
      <input
        type="checkbox"
        name="aa"
        checked={theme === 'dark'}
        onChange={(ev) => setTheme(ev.target.checked ? 'dark' : 'light')}
      />
      <span>{theme === 'dark' ? '🌞' : '🕯️'}</span>
    </div>
  );
}