Skip to content

Latest commit

 

History

History
90 lines (59 loc) · 3.25 KB

README.md

File metadata and controls

90 lines (59 loc) · 3.25 KB

scroll-behavior Travis npm package

Scroll behaviors for use with history.

Coveralls Discord

Usage

Enhance your history object with one of the scroll behaviors in this library to get the desired scroll behavior after transitions.

import createHistory from 'history/lib/createBrowserHistory'
import useScroll from 'scroll-behavior/lib/useStandardScroll'

const history = useScroll(createHistory)()

Guide

Installation

$ npm install history scroll-behavior

You may also want to install React Router to obtain a complete routing solution for React that works with history.

Scroll behaviors

useScrollToTop

useScrollToTop scrolls to the top of the page after any transition.

This is not fully reliable for POP transitions.

useSimpleScroll

useSimpleScroll scrolls to the top of the page on PUSH and REPLACE transitions, while allowing the browser to manage scroll position for POP transitions.

This can give pretty good results with synchronous transitions on browsers like Chrome that don't update the scroll position until after they've notified history of the location change. It will not work as well when using asynchronous transitions or with browsers like Firefox that update the scroll position before emitting the location change.

useStandardScroll

useStandardScroll attempts to imitate native browser scroll behavior by recording updates to the window scroll position, then restoring the previous scroll position upon a POP transition.

Custom behavior

You can further customize scroll behavior by providing a shouldUpdateScroll callback to the enhanced history. This callback is called with both the old location and the new location.

You can:

  • return a falsy value to suppress normal scroll behavior
  • return a position array such as [ 0, 100 ] to scroll to that position
  • return an otherwise truthy value to get normal scroll behavior
const history = useScroll(createHistory)({
  shouldUpdateScroll: (oldLocation, newLocation) => (
    // Don't scroll if the pathname is the same 
    newLocation.pathname !== oldLocation.pathname
  )
})
const history = useScroll(createHistory)({
  shouldUpdateScroll: (oldLocation, newLocation) => (
  	// scroll to top when attempting to vist the current path
	newLocation.pathname === oldLocation.pathname ? 
	[ 0, 0 ] : true;
  )
})

Notes

  • Support for async transitions is currently very poor. Fixing this will require major breaking API changes in the future.