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>