Skip to content

Commit c3a172d

Browse files
sidharthachatterjeepieh
authored andcommitted
fix(gatsby-react-router-scroll): Respect hash as source of truth for scroll position (#28555)
(cherry picked from commit a066a71)
1 parent 6d11da9 commit c3a172d

File tree

2 files changed

+11
-2
lines changed

2 files changed

+11
-2
lines changed

e2e-tests/production-runtime/cypress/integration/scroll-behavior.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ describe(`Scroll behaviour`, () => {
4848
cy.go(`forward`).waitForRouteChange()
4949

5050
cy.window().then(updatedWindow => {
51-
expect(updatedWindow.scrollY).not.to.eq(idScrollY)
51+
expect(updatedWindow.scrollY).to.eq(idScrollY)
5252
})
5353
})
5454
})

packages/gatsby-react-router-scroll/src/scroll-handler.tsx

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,16 @@ export class ScrollHandler extends React.Component<
6161
scrollPosition = this._stateStorage.read(this.props.location, key)
6262
}
6363

64-
if (hash && scrollPosition === 0) {
64+
/** There are two pieces of state: the browser url and
65+
* history state which keeps track of scroll position
66+
* Native behaviour prescribes that we ought to restore scroll position
67+
* when a user navigates back in their browser (this is the `POP` action)
68+
* Currently, reach router has a bug that prevents this at https://github.com/reach/router/issues/228
69+
* So we _always_ stick to the url as a source of truth — if the url
70+
* contains a hash, we scroll to it
71+
*/
72+
73+
if (hash) {
6574
this.scrollToHash(decodeURI(hash), prevProps)
6675
} else {
6776
this.windowScroll(scrollPosition, prevProps)

0 commit comments

Comments
 (0)