I'm implementing a web project with next.js and I need to update my URL dynamically when users are scrolling through the page.
For example, let's say I have 50 components on my current page (/home/components). I implemented a scroll listener to get the top component on the page. What I want to do is update the current URL with the component number. If a top component is no. 1, then my new URL should be /home/components/1.
I tried both routers. push and router. replace, but it didn't work. I also tried with shallow=true.
What happened was when the user scrolls it updates the URL but I'm gatting the page is not found after that. The reason can be there is no exact path in my implementation. Any solution for this.
const handleScroll = () => {
const baseHeaderPositions = baseHeaderRefs.current.map((ref) => {
const bounding = ref?.getBoundingClientRect();
if (!bounding) return { top: Infinity, bottom: Infinity };
return { top: bounding.top, bottom: bounding.bottom };
});
const topBaseHeaderIndex = baseHeaderPositions.findIndex(
({ top, bottom }) => top < window.innerHeight && bottom > 64,
);
// Determine which BaseHeaderSection is at the top of the viewport
if (topBaseHeaderIndex >= 0) {
setTopBaseHeaderIndex(topBaseHeaderIndex);
const currentUrl = router.asPath;
const componentId = baseHeaderDataArr[topBaseHeaderIndex]
? baseHeaderDataArr[topBaseHeaderIndex].id
: "";
// window.history.pushState({}, "", `${currentUrl}/${componentId}`);
router.push(`${currentUrl}`,`${currentUrl}/${componentId}`);
}
};
useEffect(() => {
window.addEventListener("scroll", handleScroll);
return () => {
window.removeEventListener("scroll", handleScroll);
};
}, [router, baseHeaderDataArr]);