Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

react-scrollchor

A React component for scrolling to #hash links with smooth animations

react, component, react-component, scroll, anchor, scrollchor, hash, animate

readme

react-scrollchor (React Scrollchor)

npm version npm downloads Donate

A React component for scrolling to #hash links with smooth animations. Scrollchor is a mix of Scroll and Anchor, a joke name for a useful component.

See it in action:

hash is the id attribute of an HTML tag on the current page.

Installation

npm

npm install react-scrollchor --save

yarn

yarn add react-scrollchor

Dependencies

You must have React (≥16.8.0) installed in your project before trying to use this component. This minimum version constraint represents the React version which introduced hooks.

Usage

import { Scrollchor } from 'react-scrollchor';
import { Navbar, NavItem, Page, Section } from './components';

const LandingPage = (props) => (
  <Page>

    <Navbar brand={brand} className="navbar-fixed-top">
      <NavItem><Scrollchor to="" className="nav-link">Home</Scrollchor></NavItem>
      <NavItem><Scrollchor to="#sample-code" className="nav-link">Sample</Scrollchor></NavItem>
      <NavItem><Scrollchor to="#features" className="nav-link">Features</Scrollchor></NavItem>
      <NavItem><Scrollchor to="footer" className="nav-link">SignUp</Scrollchor></NavItem>
    </Navbar>


    <Section id="sample-code">
      <div style={{ height: '100vh' }} />
    </Section>

    <div id="features">
      <div style={{ height: '100vh' }} />
    </div>

    <footer id="footer">
      <div style={{ height: '100vh' }} />
    </footer>

  </Page>
);

export default LandingPage;

Props

The package ships with TypeScript type definitions to help with IDE autocompletion, but the sections below should give you a quick rundown of each prop if you prefer this format. Any props not listed below are passed directly on to the underlying <a> tag, except for href and onClick.

The to prop controls the final href prop, and onClick is used internally to perform the scrolling. If you need to run some code when the link is clicked use the beforeAnimate prop instead.

to: string

The anchor (id) to which this link should scroll to. Any leading # will be stripped from this value.

target?: string

The element scrolling will be performed on when clicked. Leading # will be stripped here as well.

Scrollchor works within any scrollable parent container. If no target is provided (or the target element is not found on the page), the default is scrolling both the <html> and <body> elements simultaneously.

animate?: Partial<AnimateConfig>

The smooth scrolling animation can be customized using this prop. Three pre-defined easing functions are exported by the package: easeOutQuad, swing, linear. When not provided, the default looks like this:

import { AnimateConfig, easeOutQuad } from 'react-scrollchor';

const defaultAnimate: AnimateConfig = {
  offset: 0,
  duration: 400,
  easing: easeOutQuad,
};
  • offset?: number — Additional pixels to scroll relative to the target element (supports negative values, e.g. for fixed position headers)
  • duration?: number — Length of the animation in milliseconds
  • easing?: ScrollchorEasingFunction — Easing function to calculate the animation steps. Pass a function that matches the exported interface for a custom easing.

    | # | Parameter | Meaning | |---|-----------|---------| |0|percent|Percent completed of the animation (decimal, 0.0 to 1.0)| |1|elapsedTime|Time elapsed since the animation began, in ms| |2|startValue|Static value set to 0| |3|valueChange|Static value set to 1| |4|duration|Duration of the animation, in ms|

    Returns a decimal indicating how close the animation is to the end value (0 = start, 1 = finished, 1.2 = 20% over the end value, think "bounce" effects)

The default values can be customized all at once or individually by providing only the properties you want to override. For example:

import { Scrollchor, linear } from 'react-scrollchor';

const HomeLink = () => (
  <Scrollchor to="home" animate={{ duration: 1000, easing: linear }}>
    Home
  </Scrollchor>
);

You can find additional easing functions at these links:

beforeAnimate: MouseEventHandler / afterAnimate: MouseEventHandler

You can use these callbacks to trigger behaviors like: update state, load async stuff, etc. when either stage happens. The functions receive the originating MouseEvent as their only argument, the return value is not used.

beforeAnimate is triggered before the animation starts, i.e. immediately when the link is clicked, while afterAnimate is called once the animation has finished.

<Scrollchor to="#aboutus" afterAnimate={() => setActive('home')}>Home</Scrollchor>

Credits

author

maintainers

contributors

Contributing

  • Documentation improvement
  • Feel free to send any PR

License

ISC

changelog

master (unreleased)

7.0.2

  • Updated package-lock.json to avoid vulnerable dependencies reported by npm audit

7.0.1

  • Updated package-lock.json to avoid vulnerable dependencies reported by npm audit

7.0.0

This new major version contains breaking changes.

  • Everything has been rewritten in TypeScript, which brings with it published type definitions
  • The default export has been removed in favor of a named export; import Scrollchor must be replaced with import { Scrollchor }
  • The simulateClick() API has been removed entirely
  • Scrollchor is now a function component and makes use of hooks introduced in React v16.8, which necessitated a minimum version bump for this peerDependency
  • animation.easing configuration is now documented and compatible with all the easing functions provided by jquery-easing
  • Added two additional built-in easing types for ease of use, borrowed from jQuery (linear, swing)

6.0.0

Scrollchor React component now belong to Some React Component Organization Team. This move will ensure its future development and manteniance.

  • Added configurable scrollable container feature, target prop. Thanks to @xephuk dedicated effort.
  • @xehpuk join React-Schollchor Team
  • minor Doc corrections

5.1.0

  • Replace internal function updateHistory implementation for prevent scroll jumps on browser history update

5.0.2

  • Now each Scrollchor instance has its own animateScroll function that track animation state and eliminates the possibility of multiple animations interfering with each other, thanks to @xehpuk PR

5.0.1

  • Fix a state bug introduced on release 5.0.0
  • animateScroll is now asynchronous, thanks to @xehpuk PR

5.0.0

  • Add support for React 16.3.x new API
  • Prevent warning on React 16.3.x deprecated componentWillReceiveProps

4.2.1

  • Prevent error when clicking a link to an anchor that does not exist. Thanks to @SBRK contribution

4.2.0

  • Implemented animation using requestAnimationFrame. Thanks to @kambing86 PR

4.1.0

  • Add disableHistory prop for enable/disable update browser history with scroll behaviours. Default is false

4.0.0

  • Add support to changeable props. All props become responsive
  • Add simulateClick API for animate scroll programmatically
  • On childrenless Scrollchor render to null, useful for programmatically scroll
  • Add track to window.location.bash needed by browser history, back/forward buttons
  • Source refactored
  • Update Example and Demo
  • Update Doc
  • Add Credits

3.0.0

  • Add React 15.5.x support
  • Deprecate React 0.14 peer dependencie

2.2.0

  • Add beforeAnimate/afterAnimate hooks to scroll handler

2.1.3

  • Fix incorrect passed props to tag

2.1.2

  • add fbjs peer dependencie
  • improved doc

2.0.0

  • Update package
  • to prop work with and without `#
  • Add example
  • Add demo

1.0.0

  • Initial release