I want my application to go to the top of the page when another page within the site is clicked. I have used the code from: https://v5.reactrouter.com/web/guides/scroll-restoration and put in a separate file.
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;
}
What I have tried:
I have placed <ScrollToTop /> before <Switch /> and after <BrowserRouter />as in the docs (these are in separate files).
Unlike the docs, the <App /> in my application is in a separate file, so <ScrollToTop /> is not placed near it.
When I console.log, I see it being hit at the correct instance (when there is a page change), but nothing occurs. I have also looked into many stackoverflow posts concerning the same issue, but I could not incorporate their suggestions.
What are possible issues:
Calling window.scrollTo(0, 0) outside the function does not seem to work. Are there any alternatives to this function?
Is the placement of <ScrollToTop /> incorrect? Does it have to be called near the <App />?
Welcome to Stackoverflow @user19251203
You have already gone half the way. You really don't need to create a component for it. You can create a custom hook and place it in your <App /> and then call it:
function App() {
// Scroll to top on every transition custom hook
const useScrollToTop = () => {
const { pathname } = useLocation();
useEffect(() => {
window.scrollTo(0, 0);
}, [pathname]);
};
useScrollToTop();
return (
<div className="App">
.......
</div>
)
}
This way whenever you go to a new page, it scrolls to the top of the page.