Last active
January 7, 2019 11:33
Automatic top scrolling in harmony with browsers native book keeping for @reach/router
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Location } from '@reach/router' | |
import React from 'react' | |
let lastNavigationFromBrowserUI = true | |
if (typeof window !== 'undefined') { | |
window.addEventListener('popstate', event => { | |
lastNavigationFromBrowserUI = true | |
}) | |
} | |
const AutoScrollToTop = ({ children }) => ( | |
<Location> | |
{() => { | |
if (typeof history !== 'undefined') { | |
// Ininitial rendering and back/forward navigation uses browsers | |
// native scroll history mechanism which tracks scroll position | |
// for each history entry automatically | |
if (lastNavigationFromBrowserUI) { | |
lastNavigationFromBrowserUI = false | |
} else { | |
// When adding new entries by navigating through clicking on actual | |
// links in the page, we always scroll up to work around | |
// the scrolling applied by automatic focussing as done | |
// by reach routers accessibility tweaks. | |
requestAnimationFrame(() => { | |
window.scrollTo(0, 0) | |
}) | |
} | |
} | |
return children | |
}} | |
</Location> | |
) | |
export default AutoScrollToTop |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Location } from '@reach/router' | |
import React, { FunctionComponent } from 'react' | |
let lastNavigationFromBrowserUI = true | |
if (typeof (window as any) !== 'undefined') { | |
window.addEventListener('popstate', event => { | |
lastNavigationFromBrowserUI = true | |
}) | |
} | |
const AutoScrollToTop: FunctionComponent = ({ children }) => ( | |
<Location> | |
{() => { | |
if (typeof (history as any) !== 'undefined') { | |
// Ininitial rendering and back/forward navigation uses browsers | |
// native scroll history mechanism which tracks scroll position | |
// for each history entry automatically | |
if (lastNavigationFromBrowserUI) { | |
lastNavigationFromBrowserUI = false | |
} else { | |
// When adding new entries by navigating through clicking on actual | |
// links in the page, we always scroll up to work around | |
// the scrolling applied by automatic focussing as done | |
// by reach routers accessibility tweaks. | |
requestAnimationFrame(() => { | |
window.scrollTo(0, 0) | |
}) | |
} | |
} | |
return children | |
}} | |
</Location> | |
) | |
export default AutoScrollToTop |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment