I have created an next js app which has two different navbars. One navbar will be used for home and the other will be used for other routes. So in my header.js file I have this set of code -
import React, { useEffect, useState } from "react";
import { useRouter } from "next/router";
import HomeNavbar from "./Navbar/HomeNavbar";
import Navbar from "./Navbar/Navbar";
function Header() {
const router = useRouter();
const [isHome, setIsHome] = useState(false);
useEffect(() => {
if (router.pathname === "/") {
setIsHome(true);
} else {
setIsHome(false);
}
}, [router.pathname]);
return <>{isHome ? <HomeNavbar /> : <Navbar />}</>;
}
export default Header;
So when I am in home route HomeNavBar is being used and in the HomeNavBar component I have a set of code like this -
useEffect(() => {
window.onscroll = function() {
const maxHeight = 192;
const minHeight = 40;
let pixel = window.scrollY;
let pixelPosition = maxHeight - pixel;
pixelPosition = pixelPosition > maxHeight ? maxHeight : pixelPosition;
pixelPosition = pixelPosition < minHeight ? minHeight : pixelPosition;
document.getElementById("brandmark").style.cssText = `
height: ${pixelPosition}px;
width: auto;
`;
}
}, [])
It's just a basic function where I am doing something with a element containing id="brandmark"
But when I am changing the route to /about the function is still running and I am getting an error because that element with that id is not available on the about page or any other route.
How can I fix this?