简体   繁体   中英

How to scroll to the top of the page after a route change, but retain the scroll position when going back?

I want to scroll to the top of the page after changing the route. However, when the user presses the "Back" button in the browser, I want them to return to the previous scroll position on the previous page and NOT to the top. I have implemented n "scroll to the top" feature and it works ( Link ). However, I am wondering how I need to modify it to remember the previous scroll position, when going "Back".

Scroll to Top:

import React, { useEffect, Fragment } from "react";
import { withRouter } from "react-router-dom";

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

  return <Fragment>{children}</Fragment>;
}

export default withRouter(ScrollToTop);

App.js

<ScrollToTop>
   <Switch>
       <PublicRoute exact path="/join/" component={LandingPage} />
   </Switch>
</ScrollToTop>

One way you can accomplish this is by tracking where the user is via the location key and the window x, y coords. react-router-dom gives a good idea here .

Here's an example of what that might look like.

export default function ScrollRestoration() {
  const { key } = useLocation();
  const positions = useRef(new Map());

  useEffect(() => {
    if (positions.current.has(key)) {
      const { x, y } = positions.current.get(key);
      window.scrollTo(x, y);
    } else {
      window.scrollTo(0, 0);
    }

    const handler = () => {
      positions.current.set(key, { x: window.scrollX, y: window.scrollY });
    };

    window.addEventListener("scroll", handler);
    return () => {
      window.removeEventListener("scroll", handler);
    };
  }, [key]);

  return null;
}

Demo: https://codesandbox.io/s/relaxed-aryabhata-u1hgf

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM