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.
- Why is this?
- 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 :
-
react-router-domdoesn’t do scroll restoration to my best knowledge. -
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;