Skip to content

Instantly share code, notes, and snippets.

@sunnyone
Forked from ryanflorence/ManageScroll.js
Created March 20, 2019 13:37
Show Gist options
  • Save sunnyone/44aa3bdfdb49e90d20e5e53e63fd435b to your computer and use it in GitHub Desktop.
Save sunnyone/44aa3bdfdb49e90d20e5e53e63fd435b 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() {
try {
// session storage will throw for a few reasons
// - user settings
// - in-cognito/private browsing
// - who knows...
let storage = JSON.parse(sessionStorage.getItem("scrollPositions"));
if (storage) {
scrollPositions = JSON.parse(storage) || {};
let { key } = this.props.location;
if (scrollPositions[key]) {
window.scrollTo(0, scrollPositions[key]);
}
}
} catch (e) {}
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;
try {
sessionStorage.setItem(
"scrollPositions",
JSON.stringify(scrollPositions)
);
} catch (e) {}
};
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