Skip to content

Instantly share code, notes, and snippets.

@swernerx
Last active January 7, 2019 11:33
Show Gist options
  • Save swernerx/2c2ba4e611b4ec7921813a71517ddf5a to your computer and use it in GitHub Desktop.
Save swernerx/2c2ba4e611b4ec7921813a71517ddf5a to your computer and use it in GitHub Desktop.

Revisions

  1. swernerx revised this gist Jan 7, 2019. 1 changed file with 37 additions and 0 deletions.
    37 changes: 37 additions & 0 deletions AutoScrollToTop.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,37 @@
    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
  2. swernerx created this gist Jan 7, 2019.
    37 changes: 37 additions & 0 deletions AutoScrollToTop.tsx
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,37 @@
    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