Last active
September 19, 2023 18:58
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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