31 lines
737 B
JavaScript
31 lines
737 B
JavaScript
import { useEffect, useState } from 'react';
|
|||
|
|
import Icon from './Icon';
|
||
|
|
|
||
|
|
export default function ThemeToggle() {
|
||
|
|
const [theme, setTheme] = useState(null);
|
||
|
|
|
||
|
|
useEffect(() => {
|
||
|
|
setTheme(document.documentElement.dataset.theme || 'light');
|
||
|
|
}, []);
|
||
|
|
|
||
|
|
const toggle = () => {
|
||
|
|
const next = theme === 'dark' ? 'light' : 'dark';
|
||
|
|
document.documentElement.dataset.theme = next;
|
||
|
|
try {
|
||
|
|
localStorage.setItem('theme', next);
|
||
|
|
} catch (e) {}
|
||
|
|
setTheme(next);
|
||
|
|
};
|
||
|
|
|
||
|
|
return (
|
||
|
|
<button
|
||
|
|
type="button"
|
||
|
|
className="icon-button"
|
||
|
|
onClick={toggle}
|
||
|
|
aria-label={`Switch to ${theme === 'dark' ? 'light' : 'dark'} theme`}
|
||
|
|
>
|
||
|
|
<Icon name={theme === 'dark' ? 'sun' : 'moon'} />
|
||
|
|
</button>
|
||
|
|
);
|
||
|
|
}
|