How to fix Gatsby JS Link component retaining scroll position and not resetting to top
You can also modify gatsby-browser.js
and implement a hook for each scroll update:
// in gastby-browser.js
exports.shouldUpdateScroll = ({
routerProps: { location },
getSavedScrollPosition,
}) => {
const { pathname } = location
// list of routes for the scroll-to-top-hook
const scrollToTopRoutes = [`/privacy-policy`, `/page-2`]
// if the new route is part of the list above, scroll to top (0, 0)
if (scrollToTopRoutes.indexOf(pathname) !== -1) {
window.scrollTo(0, 0)
}
return false
}
You will find the code for shouldUpdateScroll
on GitHub or in the documentation for shouldUpdateScroll
on the GatsbyJS website.
If you have overflow: hidden
or overflow: auto
set on body
, you'll have this issue!
If your page is a stateless functional component, you can use the useEffect
hook to scroll back to the top of the page, assuming that you are using graphql
and so your component takes some data as an argument. This way every time that data
changes, you scroll to the top of the page(works similar to componentDidUpdate).
const PageCmp = ({ data }) => {
...
useEffect(() => {
window.scrollTo(0,0)
}, [data])
...
}