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 the internet but found a solution below that didn’t work 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;
};
Neither of the above solutions didn’t work out for me.
2
Answers
Try destructing pathname like this
or
check and remove somewhere in your css files if you have
Add the following line to some place relevant in the application (like in the index file or a router configuration file etc.)
If you’re staying within your application (not reloading or refreshing the page, so the navigation is happening internally and inside
react-router-dom
), here’s a helpful link – react-router scroll to top on every transition