-
-
Notifications
You must be signed in to change notification settings - Fork 135
/
Copy pathThemeToggle.tsx
35 lines (30 loc) · 1.06 KB
/
ThemeToggle.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
import { useState, useEffect } from "react";
const ThemeToggle = () => {
const [theme, setTheme] = useState("dark");
useEffect(() => {
// if the theme isn't set, use the user's system preference
const savedTheme = localStorage.getItem("theme");
if (savedTheme) {
setTheme(savedTheme);
document.documentElement.setAttribute("data-theme", savedTheme);
} else if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
setTheme("dark");
document.documentElement.setAttribute("data-theme", "dark");
} else {
setTheme("light");
document.documentElement.setAttribute("data-theme", "light");
}
}, []);
const toggleTheme = () => {
const newTheme = theme === "dark" ? "light" : "dark";
setTheme(newTheme);
localStorage.setItem("theme", newTheme);
document.documentElement.setAttribute("data-theme", newTheme);
};
return (
<button onClick={toggleTheme} className="button" aria-label="Toggle theme">
{theme === "dark" ? "🌞" : "🌚"}
</button>
);
};
export default ThemeToggle;