A React component for scroll to
#hashlinks with smooth animations. Scrollchor is a mix ofScrollandAnchor, 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.
npm install react-scrollchor --save- User should provide their own
Reactpackage
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> 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 }Update props will re-render Scrollchor element
Animated behavior can be customize:
<Scrollchor to="#aboutus" animate={{offset: 20, duration: 600}} className="nav-link">Home</Scrollchor>{ offset: 0, duration: 400, easing: easeOutQuad }This setting is equivalent to default jQuery.animate easing: swing
Use this callbacks to trigger behaviours like, for example, update state, load async stuffs, etc.
<Scrollchor to="#aboutus" afterAnimate={() => updateState(this)}>Home</Scrollchor>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
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); };- Jean Chung <> @jeanchung
- Chua Kang Ming <> @kambing86
- Benjamin MICHEL <> @SBRK
- Documentation improvement
- Feel free to send any PR