From 83d8c0a06bbf336c78d517528d189e5069ebe1b4 Mon Sep 17 00:00:00 2001 From: Jan Keromnes Date: Tue, 13 Apr 2021 15:54:29 +0000 Subject: [PATCH] [dashboard] Automatically update color theme on system change / storage event --- components/dashboard/src/App.tsx | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/components/dashboard/src/App.tsx b/components/dashboard/src/App.tsx index fdd98f1122afed..7c9c3ec7954b14 100644 --- a/components/dashboard/src/App.tsx +++ b/components/dashboard/src/App.tsx @@ -57,10 +57,17 @@ function App() { }, []); useEffect(() => { - if (localStorage.theme === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) { - document.documentElement.classList.add('dark'); - } else { - document.documentElement.classList.remove('dark'); + const updateTheme = () => { + const isDark = localStorage.theme === 'dark' || (!('theme' in localStorage) && window.matchMedia("(prefers-color-scheme: dark)").matches); + document.documentElement.classList.toggle('dark', isDark); + } + updateTheme(); + const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)"); + mediaQuery.addEventListener('change', updateTheme); + window.addEventListener('storage', updateTheme); + return function cleanup() { + mediaQuery.removeEventListener('change', updateTheme); + window.removeEventListener('storage', updateTheme); } }, [localStorage.theme]);