Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(gatsby-react-router-scroll): Respect hash as source of truth for scroll position #28555

Merged
merged 2 commits into from
Dec 9, 2020
Merged
Show file tree
Hide file tree
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
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ describe(`Scroll behaviour`, () => {
cy.go(`forward`).waitForRouteChange()

cy.window().then(updatedWindow => {
expect(updatedWindow.scrollY).not.to.eq(idScrollY)
expect(updatedWindow.scrollY).to.eq(idScrollY)
})
})
})
Expand Down
11 changes: 10 additions & 1 deletion packages/gatsby-react-router-scroll/src/scroll-handler.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,16 @@ export class ScrollHandler extends React.Component<
scrollPosition = this._stateStorage.read(this.props.location, key)
}

if (hash && scrollPosition === 0) {
/** There are two pieces of state: the browser url and
* history state which keeps track of scroll position
* Native behaviour prescribes that we ought to restore scroll position
* when a user navigates back in their browser (this is the `POP` action)
* Currently, reach router has a bug that prevents this at https://github.com/reach/router/issues/228
* So we _always_ stick to the url as a source of truth — if the url
* contains a hash, we scroll to it
*/

if (hash) {
this.scrollToHash(decodeURI(hash), prevProps)
} else {
this.windowScroll(scrollPosition, prevProps)
Expand Down