I'm trying to scroll on top of each page change with react-router dom v6. The code is scrolling back on top only on my home page and not on my character details page. I've tried many solutions but can't get them to work. I'm using "react-router-dom": "^6.2.2",
This is what I have achieved so far:
ScrollToTop.js:
import { useEffect } from "react";
import { useLocation } from "react-router-dom";
export default function ScrollToTop({ children }) {
const { pathname } = useLocation();
useEffect(() => {
window.scrollTo(0, 0);
}, [pathname]);
return children;
}
My app.js
<Router>
<ScrollToTop>
<Header />
<Routes>
<Route path="/" element={<Home />} />
<Route path="/character/:char_id" element={<CharacterDetail />} />
<Route path='*' element={<PageNotFound />} />
</Routes>
<Footer />
</ScrollToTop>
</Router>
I also tried doing my component directly using 'window.scrollTo(0, 0);' and by scrolling to an ID in my useEffect without success. Grateful for your guidance.