Skip to content

Instantly share code, notes, and snippets.

@ipuppyyt
Last active September 19, 2023 18:58
Show Gist options
  • Save ipuppyyt/f767f9aba74e70b235e6b867964c1724 to your computer and use it in GitHub Desktop.
Save ipuppyyt/f767f9aba74e70b235e6b867964c1724 to your computer and use it in GitHub Desktop.
A React JSX device theme selector function that updates itself upon device theme update. Updates Realtime.
const useThemeDetector = () => {
const getCurrentTheme = () => {
if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
return "dark";
}
return "light";
}
const [theme, setTheme] = useState (getCurrentTheme());
document.querySelector("body").setAttribute("data-theme", theme);
localStorage.setItem("theme", theme);
useEffect(() => {
const darkThemeMq = window.matchMedia("(prefers-color-scheme: dark)");
darkThemeMq.addListener(e => {
setTheme(e.matches ? "dark" : "light")
});
return () => darkThemeMq.removeListener(e => {
setTheme(e.matches ? "dark" : "light")
});
}, []);
return theme;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment