Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug in the dark mode functionality #85

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 19 additions & 2 deletions 12-atomic-blog/final/src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -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]
);
Expand Down