Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix Gatsby JS Link component retaining scroll position and not resetting to top

Tags:

reactjs

gatsby

I'm setting up a website using Gatsby 2.2.10 and the Link components are retaining the scroll positions of the previous page and not scrolling back to the top when they're clicked.

<div className="Footer__legal body">
 <p>© {new Date().getFullYear()} My Nice Company</p>
 <Link to="/privacy-policy">Privacy Policy</Link>
 <Link to="/page-2">Page 2 Link component</Link>
</div>

Expected behaviour:

When you click 'Privacy Policy', 'Page 2' or any page at the bottom of the website, I expect the page to load with user being back at the top.

Actual Behaviour:

User stays at scroll position of the current page

like image 756
Jack David Evans Avatar asked Mar 25 '19 11:03

Jack David Evans


2 Answers

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.

like image 189
Michael Czechowski Avatar answered Oct 24 '22 11:10

Michael Czechowski


If you have overflow: hidden or overflow: auto set on body, you'll have this issue!

like image 8
Addison Avatar answered Oct 24 '22 11:10

Addison