react check if browser is in dark mode

Solutions on MaxInterview for react check if browser is in dark mode by the best coders in the world

showing results for - "react check if browser is in dark mode"
Francesca
02 Nov 2020
1if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
2    // dark mode
3}
4
5//To watch for changes:
6
7window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {
8    const newColorScheme = e.matches ? "dark" : "light";
9});
10
11//Or in React Hooks:
12
13const [mode, setMode] = useState<"light" | "dark" | undefined>(
14    window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches ? "dark" :"light"
15);
16
17useEffect(() => {
18  const modeMe = (e: any) => {
19    setMode(e.matches ? "dark" : "light");
20  }  
21  window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', modeMe);
22  return window.matchMedia('(prefers-color-scheme: dark)').removeListener(modeMe);
23}, []);
24