skip to Main Content

I’m encountering an issue in my ReactJS application where, upon navigating to a new page, the page automatically scrolls down to a position below the top of the page instead of starting from the top (generally it takes scroll position from the previous page). This behavior is inconsistent with typical page navigation where the new page should load from the top.

I’ve looked into possible solutions but haven’t found one that works for me. I found a lot on the internet but found a solution below that didn’t work for me. Can someone please advise on how to ensure that when navigating between pages, the new page consistently loads from the top instead of scrolling down?

Any help or insights would be greatly appreciated. Thank you!

const ScrollToTop = () => {
  const history = useHistory();

  useEffect(() => {
    const unlisten = history.listen(() => {
      window.scrollTo(0, 0);
    });
    return () => {
      unlisten();
    };
  }, [history]);

  return null;
};
const ScrollToTop = () => {
  const {pathname} = useLocation();
  useEffect(() => {
      window.scrollTo(0, 0);
  }, [pathname]);

  return null;
};

Neither of the above solutions didn’t work out for me.

2

Answers


  1. Try destructing pathname like this

    const ScrollToTop = () => {
      const {pathname} = useLocation();
      useEffect(() => {
          window.scrollTo(0, 0);
      }, [pathname]);
    
      return null;
    };
    

    or
    check and remove somewhere in your css files if you have

    scroll-behavior: auto
    
    Login or Signup to reply.
  2. Add the following line to some place relevant in the application (like in the index file or a router configuration file etc.)

    window.history.scrollRestoration = 'manual'
    

    If you’re staying within your application (not reloading or refreshing the page, so the navigation is happening internally and inside react-router-dom), here’s a helpful link – react-router scroll to top on every transition

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search