Skip to content
This repository has been archived by the owner on Apr 20, 2023. It is now read-only.

Handle scrolling to hash on page transition #38

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 22 additions & 1 deletion src/PageTransition.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,21 @@ function makeStateUpdater(state, otherProps) {
}
}

function scrollToHash() {
// Function lifted from
// https://github.com/zeit/next.js/blob/master/packages/next/client/index.js
let { hash } = window.location
hash = hash && hash.substring(1)
if (!hash) return

const el = document.getElementById(hash)
if (!el) return

// If we call scrollIntoView() in here without a setTimeout
// it won't scroll properly.
setTimeout(() => el.scrollIntoView(), 0)
}

class PageTransition extends React.Component {
constructor(props) {
super(props)
Expand Down Expand Up @@ -122,7 +137,13 @@ class PageTransition extends React.Component {
const shouldAnimateTransition =
needsTransition &&
differentChildrenNeedAnimation(renderedChildren, children)
if (isIn && needsTransition && !shouldAnimateTransition) {
if (isIn && !needsTransition && state === 'enter') {
// We just began transitioning the current page in - this means that the
// page now exists in the DOM, and thus it's safe to scroll to the
// current hash (if one exists).
// See https://github.com/illinois/next-page-transitions/issues/35
scrollToHash()
} else if (isIn && needsTransition && !shouldAnimateTransition) {
// We need to update our rendered children, but we shouldn't animate them.
// This will occur when the key prop on our children stays the same but
// the children themselves change. This can happen in a lot of cases: HMR,
Expand Down