From 8c2151dcf325ceb0381593a8e7f5c8d7f84a7567 Mon Sep 17 00:00:00 2001 From: aarya-16 Date: Fri, 25 Oct 2024 14:46:57 +0530 Subject: [PATCH] Added event listener and older browser support --- Client/src/App.jsx | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/Client/src/App.jsx b/Client/src/App.jsx index c8fb60d54..cccd4c6a7 100644 --- a/Client/src/App.jsx +++ b/Client/src/App.jsx @@ -42,11 +42,14 @@ import { networkService } from "./main"; import { setMode } from "./Features/UI/uiSlice"; const getPreferredTheme = () => { - if(window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) { - return 'dark'; + try { + return window?.matchMedia?.('(prefers-color-scheme: dark)')?.matches? 'dark': 'light'; + } + catch { + return 'light'; } - return 'light'; } + function App() { const AdminCheckedRegister = withAdminCheck(Register); const MonitorsWithAdminProp = withAdminProp(Monitors); @@ -69,6 +72,17 @@ function App() { useEffect(() => { const theme = getPreferredTheme(); dispatch(setMode(theme)); + + const mediaQuery = window?.matchMedia?.('(prefers-color-scheme: dark)'); + const handleThemeChange = (e) => { + dispatch(setMode(e.matches ? 'dark' : 'light')); + }; + + mediaQuery?.addEventListener?.('change', handleThemeChange); + + return () => { + mediaQuery?.removeEventListener?.('change', handleThemeChange); + }; },[dispatch]); // Cleanup