I’m encountering an issue in my ReactJS application where, upon navigating to a new page, the page automatically scrolls down to a position below the top of the page instead of starting from the top (generally it takes scroll position from the previous page). This behavior is inconsistent with typical page navigation where the new page should load from the top.
I’ve looked into possible solutions but haven’t found one that works for me. I found a lot on internet but found a below solution that didn’t works for me. Can someone please advise on how to ensure that when navigating between pages, the new page consistently loads from the top instead of scrolling down?
Any help or insights would be greatly appreciated. Thank you!
const ScrollToTop = () => {
const history = useHistory();
useEffect(() => {
const unlisten = history.listen(() => {
window.scrollTo(0, 0);
});
return () => {
unlisten();
};
}, [history]);
return null;
};
const ScrollToTop = () => {
const pathname = useLocation();
useEffect(() => {
window.scrollTo(0, 0);
}, [pathname]);
return null;
};
Both of the above solutions didn’t work out for me.