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

Fixed the theme changing when reload issue, Issue #1187 #1188

Open
wants to merge 1 commit into
base: master
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
27 changes: 16 additions & 11 deletions components/Sidebar.jsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,26 @@
import React, { useState } from "react";
import React, { useState, useEffect } from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faCode, faMoon, faSun } from "@fortawesome/free-solid-svg-icons";

function Sidebar() {
const [theme, setTheme] = useState("dark");

function toggleTheme() {
const htmlElement = document.documentElement;
const isDarkModeEnabled = htmlElement.classList.contains("dark");
useEffect(() => {
const savedTheme =
typeof window !== "undefined" ? localStorage.getItem("theme") : "dark";
if (savedTheme) {
setTheme(savedTheme);
document.documentElement.classList.toggle("dark", savedTheme === "dark");
}
}, []);

if (isDarkModeEnabled) {
htmlElement.classList.remove("dark");
setTheme("light");
} else {
htmlElement.classList.add("dark");
setTheme("dark");
function toggleTheme() {
const newTheme = theme === "dark" ? "light" : "dark";
setTheme(newTheme);
if (typeof window !== "undefined") {
localStorage.setItem("theme", newTheme);
}
document.documentElement.classList.toggle("dark", newTheme === "dark");
}

return (
Expand All @@ -36,7 +41,7 @@ function Sidebar() {
className="h-10 w-10 cursor-pointer rounded-lg border-2 border-borderSecondary bg-white transition-all hover:border-textSecondary hover:text-textSecondary dark:border-borderColor dark:bg-textPrimary dark:text-white dark:hover:border-textSecondary dark:hover:text-textSecondary"
onClick={toggleTheme}
>
{theme === "light" ? (
{theme === "dark" ? (
<FontAwesomeIcon icon={faMoon} fontSize="1rem" />
) : (
<FontAwesomeIcon icon={faSun} fontSize="1rem" />
Expand Down