Skip to content

Instantly share code, notes, and snippets.

@volkancakil
Forked from ryanflorence/ManageScroll.js
Created August 13, 2018 22:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save volkancakil/2ad8462b190b04096f53491625a0f67d to your computer and use it in GitHub Desktop.
Save volkancakil/2ad8462b190b04096f53491625a0f67d to your computer and use it in GitHub Desktop.
import React from "react";
import { Location } from "@reach/router";
let scrollPositions = {};
class ManageScrollImpl extends React.Component {
componentDidMount() {
let storage = sessionStorage.getItem("scrollPositions");
if (storage) {
scrollPositions = JSON.parse(storage);
let { key } = this.props.location;
if (scrollPositions[key]) {
window.scrollTo(0, scrollPositions[key]);
}
}
window.addEventListener("scroll", this.listener);
}
componentWillUnmount() {
window.removeEventListener("scroll", this.listener);
}
componentDidUpdate() {
const { key } = this.props.location;
if (!scrollPositions[key]) {
// never seen this location before
window.scrollTo(0, 0);
} else {
// seen it
window.scrollTo(0, scrollPositions[key]);
}
}
listener = () => {
scrollPositions[this.props.location.key] = window.scrollY;
sessionStorage.setItem("scrollPositions", JSON.stringify(scrollPositions));
};
render() {
return null;
}
}
export default () => (
<Location>
{({ location }) => <ManageScrollImpl location={location} />}
</Location>
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment