Scroll Restoration on page change doesn't fully scroll to top

372 Views Asked by At

Scroll restoration scrolls 8/10ths of the way up the page but not all the way. Not sure if my ScrollToTop component is flawed or if I'm using the route and switch tags incorrectly in the App component. Below are the ScrollToTop and App components respectively.

import { useEffect } from "react";
import { useLocation } from "react-router-dom";

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

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

  return null;
}

export default ScrollToTop;
return (
    <div className="App">
      <Switch>
        <Route path='/explore'>
          <ScrollToTop />
          <Layout className='' currentUser={currentUser} posts={posts} handleLogout={handleLogout}>
            <Explore posts={posts} />
          </Layout >
        </Route>
        <Route path='/meta'>
          <ScrollToTop />
          <Layout currentUser={currentUser} posts={posts} handleLogout={handleLogout}>
            <Meta currentUser={currentUser} posts={posts} />
          </Layout>
        </Route>
        <Route path='/mana'>
          <ScrollToTop>
            <Layout currentUser={currentUser} posts={posts} handleLogout={handleLogout}>
              <Mana currentUser={currentUser} posts={posts} />
            </Layout>
          </ScrollToTop>
        </Route>
        <Route path='/crypto'>
          <ScrollToTop />
          <Layout currentUser={currentUser} posts={posts} handleLogout={handleLogout}>
            <Crypto currentUser={currentUser} posts={posts} />
          </Layout>
        </Route>
        <Route path='/film'>
          <ScrollToTop />
          <Layout currentUser={currentUser} posts={posts} handleLogout={handleLogout}>
            <Film currentUser={currentUser} posts={posts} />
          </Layout>
        </Route> 
      </Switch>
    </div >
  );
}

export default App; 
2

There are 2 best solutions below

1
Mirko Acimovic On

If you want to use window object to perform scroll :

window.scroll({top:0,behavior:'smooth'})
7
iamalinski On

Try this:

document.querySelector('body').scrollIntoView({ 
  block: "start"
})