This is the Next JS code for Navbar on all pages, initially it changes the color of the elements from white to black when scrolling below 950 px, but I want the Navbar elements on another page "/lodge/page.tsx" not to change color after 950px from white to black, but to be initially black, because on this page the background is white and the elements are just not visible.
'use client'
import Image from "next/image"
import Link from "next/link"
import Container from "../Container"
import Logo from "./Logo"
import Contacts from "./Contacts"
import Lang from "./Lang"
import { useState, useEffect } from "react";
const Navbar = () => {
const [color, setColor] = useState(false)
const changeColor = () => {
if (window.scrollY >= 950 && !window.location.pathname.includes('/lodge/page.tsx')) {
setColor(true)
}
else {
setColor(false)
}
}
window.addEventListener('scroll', changeColor)
return (
<div className="fixed w-full backdrop-blur-sm shadow-sm">
<div className="py-4 border-b-[2px]">
<Container>
<div className="flex flex-row items-center justify-between gap-4">
<Logo />
<div className="text-2xl text-white font-medium xl:pl-[632px] md:block hidden">
<Link
href="/lodge"
className={color ? 'text-[#313131]' : 'text-white'}
>
LODGE
</Link>
</div>
<div className="text-2xl text-white font-medium md:block hidden">
<div className={color ? 'text-[#313131]' : 'text-white'}>
<Link href="/blog">
OUR BLOG
</Link>
</div>
</div>
<Contacts />
<Lang />
</div>
</Container>
</div>
</div>
)
}
export default Navbar
I tried adding a condition – (window.scrollY >= 950 && !router.pathname.includes('/lodge/page.tsx'))
, but it doesn’t work.
2
Answers
The condition you’re using is not correct.
(window.scrollY >= 950 && !window.location.pathname.includes('/lodge/page.tsx'))
means that the color will be black when scrolling BELOW 950px (window.scrollY >= 950
) while NOT on the/lodge/page.tsx
.Simply remove the exclamation mark and change
>=
to<=
:Edit: I understand now that you wish to apply that conditional color toggling globally an not only in
/lodge/page.tsx
, Here’s the code:It looks like you’re trying to conditionally change the color of your Navbar elements based on the scroll position and the current page path in a Next.js application. The condition you’re using should work with a slight modification. Here’s how you can achieve the desired behavior:
In this modified code:
We import the
useRouter
hook from Next.js to access the current route information.We use the
useEffect
hook to add the scroll event listener and remove it when the component unmounts.Inside the
changeColor
function, we checkrouter.pathname
(the current page path) against ‘/lodge/page’. If it’s not the ‘/lodge/page’ path, and the scroll position is greater than or equal to 950, we set thecolor
state totrue
.This should ensure that the Navbar elements are initially black and only change color when the conditions are met on pages other than ‘/lodge/page’.