From 1aaa8e38ff2c9dbd7c2f38869c6d2f019ae7f509 Mon Sep 17 00:00:00 2001 From: Mamatha1718 Date: Fri, 27 Dec 2024 10:54:13 +0530 Subject: [PATCH] user's choice of dark or light mode #57 --- src/index.tsx | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/src/index.tsx b/src/index.tsx index eac60e8..daa654b 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -54,17 +54,22 @@ type DarkModeState = { function useDarkMode(): [boolean, Function] { const systemDarkMode = useMediaQuery("(prefers-color-scheme: dark)"); - const [state, setState] = React.useState({ - system: systemDarkMode, - user: localStorage.getItem("theme") === "dark", - } as DarkModeState); + const [darkMode, setDarkMode] = React.useState(() => { + const storedPreference = localStorage.getItem("theme"); + return storedPreference ? storedPreference === "dark" : systemDarkMode; + }); - function setDarkMode(value: boolean) { - localStorage.setItem("theme", value? "dark" : "light"); - setState({ ...state, user: value }); + React.useEffect(() => { + document.body.setAttribute("color-scheme",darkMode ? "dark" : "light"); + }, [darkMode]); + + function toggleDarkMode() { + const newMode = !darkMode; + localStorage.setItem("theme", newMode ? "dark" : "light"); + setDarkMode(newMode); } - const darkMode = state.user === undefined ? systemDarkMode : state.user; - return [darkMode, setDarkMode]; + + return[darkMode, toggleDarkMode]; } export default function Root() {