I have a results.tsx and detail.tsx. I store the scroll position on the results component in location.state to scroll to that position when the user returns to the results page using the browser’s back button. But when I go to a detail page from the results page, the detail page overwrites the scroll position. I scroll to the top on the detail page because the detail page takes the scroll position of the results page. I don’t understand why they use each other’s scroll position? How can I avoid this? I use Link element to navigate to detail page. Does it happen because of that?
results.tsx
const handlePageChange = (newPage: number) => {
navigate(location.pathname, {
state: { currentPageNumber: newPage, scrollPosition: 0 },
});
};
const handleScroll = () => {
const currentScrollPosition = window.scrollY;
navigate(location.pathname, {
state: { ...location.state, scrollPosition: currentScrollPosition },
});
};
useEffect(() => {
const savedPage = location.state?.currentPageNumber || 1;
const savedScrollPosition = location.state?.scrollPosition || 0;
setPageNumber(savedPage);
window.scrollTo(0, savedScrollPosition);
window.addEventListener("scroll", handleScroll);
return () => {
window.removeEventListener("scroll", handleScroll);
};
}, [location.state]);
<Link className={styles.name} to={`/detail/${movie.id}`}>
<h3>{movie.name}</h3>
</Link>
I deleted the scroll-top code in the detail component, and when I return to the results page, it scrolls to the correct position, but this time the detail page also scrolls to that position.