From 6d86686e942f5aa9caaa93c60e19ca8028528226 Mon Sep 17 00:00:00 2001 From: Erick ngechu Date: Thu, 5 Sep 2024 17:15:45 +0300 Subject: [PATCH] Update App.js Changes made are on the isFakeDark mode feature. Initially when the application runs at first,there is a conflict between the default darkmode settings (which may occur on diffrent users machines) and the state setting which by default is set to false. To solve this, I have included code which checks if there is any user predefined theme on the local storage or any system defined theme at component mount. On the useEffect, the "fake-dark-mode" class is toggled respectively while updating the localstorage theme as per the isFakeDark state. --- 12-atomic-blog/final/src/App.js | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/12-atomic-blog/final/src/App.js b/12-atomic-blog/final/src/App.js index ee26fb8740..6ff66aafd3 100644 --- a/12-atomic-blog/final/src/App.js +++ b/12-atomic-blog/final/src/App.js @@ -11,11 +11,28 @@ function createRandomPost() { function App() { // Whenever `isFakeDark` changes, we toggle the `fake-dark-mode` class on the HTML element (see in "Elements" dev tool). - const [isFakeDark, setIsFakeDark] = useState(false); + const [isFakeDark, setIsFakeDark] = useState(()=>{ + /*Checking Local Storage theme at mount for user prefences*/ + const storedTheme = localStorage.getItem("theme"); + if(storedTheme){ + return storedTheme === "dark"; + } + + /*Return to system prefrence if user has not set any preference*/ + return window.matchMedia("(prefers-color-scheme: dark)").matches; + }); useEffect( function () { - document.documentElement.classList.toggle("fake-dark-mode"); + /*Add or remove the "fake-dark-mode" class on the root element based on the state*/ + if(isFakeDark){ + document.documentElement.classList.add("fake-dark-mode"); + localStorage.setItem("theme","dark") + }else{ + document.documentElement.classList.remove("fake-dark-mode"); + localStorage.setItem("theme","light") + } + }, [isFakeDark] );