A React component for scroll to #hash links with smooth animations
React Scrollchor
A React component for scroll 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:
- demo video
- example page and source code
hash
is the id
of a HTML tag on current page.
Installation
npm
npm install react-scrollchor --save
Dependencies
- User should provide their own
React
package
Usage
import Scrollchor from 'react-scrollchor';
export default (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">
</Section>
<div id="features">
</div>
<footer id="footer">
</footer>
</Page>
Prop types
propTypes: {
/**
* id attribute of target DOM node
* - `#` can be omited
* - let it blank, `to = ''`, for scroll to page top
* - this prop it's required
*/
to: PropTypes.string.isRequired,
/**
* scroll smooth animation can be customize
* Accepted options, Ex: (default)
* { offset: 0, duration: 400, easing: easeOutQuad }
*/
animate: PropTypes.object,
/**
* callback function triggered before scroll to #hash
* @param1 Received click event
*/
beforeAnimate: PropTypes.func,
/**
* callback function triggered after scroll to #hash
* @param1 Received click event
*/
afterAnimate: PropTypes.func
/**
* enable/disable update browser history with scroll behaviours
* Default to `false`
*/
disableHistory: PropTypes.bool
}
Reactive props
Update props
will re-render Scrollchor
element
Custom animation
Animated behavior can be customize:
<Scrollchor to="#aboutus" animate={{offset: 20, duration: 600}} className="nav-link">Home</Scrollchor>
default animation settings
{ offset: 0, duration: 400, easing: easeOutQuad }
This setting is equivalent to default jQuery.animate easing: swing
more Easing
functions
before
and after
Animate callbacks
Use this callbacks to trigger behaviours like, for example, update state, load async stuffs, etc.
<Scrollchor to="#aboutus" afterAnimate={() => updateState(this)}>Home</Scrollchor>
Simulate click API
Scrollchor include a dedicate API for init animate scroll programmatically that works like normal click events using simulateClick()
When used programmatically some use-case don't need anchor tags
. On this cases use childrenless Scrollchor
Childrenless Scrollchor
This component will render null
and the user it's reponsible of store the component reference, Ex: childrenless
<Scrollchor ref={ref => (this._back = ref)} to="_back" />
Ex: calling simulateClick()
on childrenless ref
_afterAnimate = () => {
this.setState({ to: this._iterator.next().value });
setTimeout(() => this._back.simulateClick(), 1000);
};