Search code examples
htmlreactjshyperlinkjsxreact-router-dom

React Router Dom: Why does <Link /> correctly navigates to desired path/page but doesn't update the scrollY position to the top of the new path/page?


I have a simple React application that has a Home and Privacy Policy page. When using <Link /> from react-router-dom the current page scrollY position is maintained from path A to path B.

My home page has a footer at the bottom of the page. When I scroll to the bottom of the page and click on the Privacy Policy link it correctly takes me from the root path (/) to the new path of /privacy but I am not at the top of the privacy page when I get there. It maintains the scrollY position.

  1. Why is this?
  2. How should I be doing this to correctly navigate to the privacy policy and arrive at the top of the page?

I am importing like so: import { Link } from "react-router-dom"; My link looks like this: <Link to="/privacy">Privacy Policy</Link>


Solution

    1. react-router-dom doesn't do scroll restoration to my best knowledge.

    2. Try using useLayoutEffect.

    Import it from react and use the following inside your Privacy page. This will allow you use window.scrollTo().

    import { useLayoutEffect } from "react";
    
    const Privacy = () => {
      useLayoutEffect(() => {
        window.scrollTo(0, 0);
      }, []);
      return <div>... your code</div>;
    };
    
    export default Privacy;