I have a React app and I had to use Scroll To Top. I have used this before many times, and never had problems as explained:
https://reactrouter.com/web/guides/scroll-restoration/scroll-to-top
The funny thing is I can't get it working now for some reason. I tried many ways, I changed the structure of my Router, and still doesn't work.
What really happens is I get the last window position of the component before the Route change, and I obviously want to position to top on each Route change
This is my ScrollToTop.js
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;
}
This is inside my App.js
<Router basename={'/'}>
<NavMobile />
<Cart />
<ScrollToTop />
<Switch>
<Route exact path="/home" component={Home} />
<Route exact path="/book" component={Book} />
</Switch>
</Router>