I am using the following ScrollToTop component to scroll to the top of the page after navigating to a new page with react-router (copied from somewhere here at SO). This works as intended.
import { useEffect } from "react";
import { useLocation } from "react-router-dom";
export default function ScrollToTop() {
const { pathname } = useLocation();
useEffect(() => {
window.scrollTo(0, 0);
}, [pathname]);
return null;
}
<ScrollToTop />
is located within my App.js right below my react-helmet
and above my <Header />
component.
However, when navigating to the current page (e.g. I open website/about, scroll down and navigate to website/about again), then I stay at the current position without scrolling back to the top. I am assuming this is the case because the component doesn't get reloaded?
What I would expect/like to happen is that the page scrolls to the top on every navigation, even when navigating to the current page.
How can I achieve this?
Allright - after looking around and fiddling some more, I stumbled upon this right here: stackoverflow: react-router scroll to top on every transition
I discarded this at first because I assumed it would do pretty much the same thing as my code. Boy was I wrong. This code does exactly what I was looking for.
Only one thing: I was getting an error about a missing dependency:
React Hook useEffect has a missing dependency: 'history'.
Adding history to the dependencies fixed this issue. Here the final code, mostly copied from the post linked above:
import { useEffect } from "react";
import { withRouter } from "react-router-dom";
function ScrollToTop({ history }) {
useEffect(() => {
const unlisten = history.listen(() => {
window.scrollTo(0, 0);
});
return () => {
unlisten();
};
}, [history]);
return null;
}
export default withRouter(ScrollToTop);