In the following code
import { useEffect } from "react";
import Link from "next/link";
import styles from "./header.module.css";
import { useRouter } from "next/router";
export default function Header() {
const router = useRouter();
const handleClick = (path) => {
if (path === "/mvg") {
console.log("I clicked on the mvg Page");
}
};
useEffect(() => {
const header = document.querySelector("header");
const nav = document.querySelector("nav");
if (router.pathname === "/") {
header.classList.add("headerTest");
nav.classList.add("menuTest");
}
}, []);
useEffect(() => {
const header = document.querySelector("header");
const nav = document.querySelector("nav");
function checkScroll() {
if (window.innerWidth <= 768) {
header.classList.remove("headerTest");
nav.classList.remove("menuTest");
}
if (window.scrollY === 0) {
header.classList.add("headerTest");
nav.classList.add("menuTest");
}
}
window.addEventListener("scroll", checkScroll);
// Remove event listener on cleanup
return () => window.removeEventListener("resize", checkScroll);
}, []); // Empty array ensures that effect is only run on mount
return (
<header className={styles.header}>
<h1>
<Link href="/">
<a>
<span className="offscreen">Home</span>
</a>
</Link>
</h1>
<nav id="menu" className={styles.menu}>
<ul>
<li>
<Link href="/mvg">
<a onClick={() => handleClick("/mvg")}>MVG</a>
</Link>
</li>
</ul>
</nav>
</header>
);
}
I'd like my header background to be blue and its menu item text be white when the user arrives on the home page by adding classes in my pages/globals.css, which I achieve with
if (router.pathname === "/") {
header.classList.add("headerTest");
nav.classList.add("menuTest");
}
Then when the user scrolls down on the home page, I want the header to be white and the menu item text to return to its default. But when the user scrolls back to the top, I want the header to be blue and its menu item text be white again, which I achieve with my checkScroll function.
My problem is that when the user clicks on the mvg page link, I want the header to be white and its menu item text be its default color on the mvg page arrival, when the mvg page is scrolled down, and when the mvg page is scrolled to the top.
The current code fails the last condition so that whenever the mvg page is scrolled to the top, the mvg page header is blue and its menu item text is white, from the same checkScroll function.
How do I revise my code so that the mvg page header is blue and its menu item text be the default color when the user scrolls to the top while still having my home page header be white and its menu item text be white when scrolled to the top?
My codesandbox