From 17a673a69a62dd450ca2fa5e5a6141ec329ce5dc Mon Sep 17 00:00:00 2001 From: Sammy-T Date: Sun, 25 Jul 2021 02:42:13 -0400 Subject: [PATCH] Preserve page's scroll position --- components/layout/Page.js | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/components/layout/Page.js b/components/layout/Page.js index 28492ddf..3fbd7673 100644 --- a/components/layout/Page.js +++ b/components/layout/Page.js @@ -2,6 +2,25 @@ import React from 'react'; import classNames from 'classnames'; import styles from './Page.module.css'; -export default function Page({ className, children }) { - return
{children}
; +export default class Page extends React.Component { + getSnapshotBeforeUpdate() { + if (window.pageXOffset === 0 && window.pageYOffset === 0) return null; + + // Return the scrolled position as the snapshot value + return { x: window.pageXOffset, y: window.pageYOffset }; + } + + /* eslint-disable no-unused-vars */ + componentDidUpdate(prevProps, prevState, snapshot) { + if (snapshot !== null) { + // Restore the scrolled position after re-rendering + window.scrollTo(snapshot.x, snapshot.y); + } + } + /* eslint-enable no-unused-vars */ + + render() { + const { className, children } = this.props; + return
{children}
; + } }