React-static: [Docs] Scroll on top when changing page

Created on 25 Apr 2020  路  3Comments  路  Source: react-static/react-static

Hello,

First of all thanks for react-static !

I'm currently looking for a way to reset the scroll to the top page when changing pages. I've saw an issue about it #551 with autoScrollToTop={true} on the <Router> but it did not work and seems to be deprecated since it not longer mentionned on the doc. So what's the way to do that ?

Thanks for your help !

documentation

Most helpful comment

It depends on your router. The easiest thing is something like this:

export default function ScrollToTop() {
  const { pathname } = useLocation();

  useEffect(() => {
    window.scrollTo(0, 0);
  }, [pathname]);

  return null;
}

You would then "just" mount this inside the router:

<Root>
  <ScrollToTop />
...

All 3 comments

It depends on your router. The easiest thing is something like this:

export default function ScrollToTop() {
  const { pathname } = useLocation();

  useEffect(() => {
    window.scrollTo(0, 0);
  }, [pathname]);

  return null;
}

You would then "just" mount this inside the router:

<Root>
  <ScrollToTop />
...

@SleeplessByte This works great except that it also scrolls to the top when you go back.

That's correct. This is ScrollToTop, not "ScrollRestoration".

Was this page helpful?
0 / 5 - 0 ratings

Related issues

bard picture bard  路  3Comments

josephdburdick picture josephdburdick  路  4Comments

josephdburdick picture josephdburdick  路  4Comments

calvinrbnspiess picture calvinrbnspiess  路  4Comments

bkniffler picture bkniffler  路  3Comments