skip to Main Content

Without specific code, I will briefly describe a phenomenon I encountered when using react-router. <Link></Link> to do a route jump, I scroll a certain distance in the current page to click one of the pages. <Link></Link> when the label contains a route, after the jump, the scroll bar is not at the top of the new page, but still in the same position as it was just before the jump, which is strange

2

Answers


  1. I think this problem is related to scrolling behavior when using React Router’s component. By default, when you navigate using a link, React Router will try to scroll to the element with the ID specified in the URL hash.

    If you want to ensure that the new page always starts at the top when navigating, you can use the useEffect hook in your page components to scroll to the top when the component mounts.

    I add some example codeÏ:

    useEffect(() => {
      // Scroll to the top when the component mounts
      window.scrollTo(0, 0);
    }, []);
    
    Login or Signup to reply.
  2. The problem you’re facing with the scroll position may be arises because the browser is maintaining the scroll position from the previous page.

    "You can use the useEffect hook to scroll to the top of the page whenever the route changes."

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

    If you’re using BrowserRouter from react-router-dom, you can use its scrollToTop prop.

       <BrowserRouter scrollToTop={true}>
            
        </BrowserRouter>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search