I want to change the color of my navbar from transparent to ‘bg-red-50’ when I start scrolling. Following is my approach to this issue. The background is transparent and isn’t changing on scroll. Moreover, nothing is being logged to console suggesting that handleScroll
function isn’t being called at all.
"use client";
import { useEffect, useState } from "react";
const NavLayout = ({ layout, children }) => {
const [scrolling, setScrolling] = useState(false);
useEffect(() => {
const handleScroll = () => {
if (window.scrollY > 0) {
setScrolling(true);
} else {
setScrolling(false);
}
};
window.addEventListener("scroll", handleScroll);
return () => {
window.removeEventListener("scroll", handleScroll);
};
}, []);
return (
<nav
className={`${layout} absolute top-3 left-3 w-[98%] rounded py-2 px-10 text-xl ${
scrolling ? "bg-red-50" : ""
} z-50 h-[70px]`}
>
{children}
</nav>
);
};
export default NavLayout;
Can anyone point out what I am doing wrong?
2
Answers
First make sure you have imported and used the ‘NavLayout’ component correctly in your application,then make sure that you are using a browser that supports the scroll event and if there are any other event listeners on the window object that might conflict with your scroll event listener.
You can use
useRef
instead of usingstate
to manage scrolled or not. Because you don’t want to re-render multiple times when scrolling, its basically affect the performance.