Lightweight library for smooth scrolling anchors in React, tied to URL hash.
- Land on correct anchor when page is loaded, based on URL hash value.
- Scroll smoothly to anchors when URL hash changes. Easy links to sections with
<a href='#sectionId'>
. - URL hash updates automatically to reflect section in view
- Option to record history on hash changes
npm install --save react-scrollable-anchor
To run examples locally, npm run example
, then open your
browser to localhost:3210.
Use the ScrollableAnchor
tag to wrap any React element, making it a scrollable anchor.
import React, { Component } from 'react'
import ScrollableAnchor from 'react-scrollable-anchor'
export default class Page extends Component {
render() {
return (
<div>
<a href='#section1'> Go to section 1 </a>
<a href='#section2'> Go to section 2 </a>
<ScrollableAnchor id={'section1'}>
<div> Hello World </div>
</ScrollableAnchor>
<ScrollableAnchor id={'section2'}>
<div> How are you world? </div>
</ScrollableAnchor>
</div>
)
}
}
The ScrollableAnchor
component has a optional customHashUpdater
(function) prop, that overrides the default one.
This is useful when you have problems especially with react-router
doing complete re-renders of the Route
component
that results in jumping to the top of the component after scrolling to a different section.
The customHashUpdater
receives the id of the section and can be used like this:
// Uses the react-router history prop
const goToSection = id => history.push({ hash: `#${id}` });
<ScrollableAnchor id={'section1'} cu>
<div> Hello World </div>
</ScrollableAnchor>
Access configureAnchors to customize scrolling and anchors.
import { configureAnchors } from 'react-scrollable-anchor'
// Offset all anchors by -60 to account for a fixed header
// and scroll more quickly than the default 400ms
configureAnchors({offset: -60, scrollDuration: 200})
option | default |
---|---|
offset |
0 |
scrollDuration |
400 |
keepLastAnchorHash |
false |
A small toolkit of scrolling utilies for use with anchors
import { goToTop } from 'react-scrollable-anchor'
// scroll to top of the page
goToTop()
import { goToAnchor } from 'react-scrollable-anchor'
// scroll to #section1 without saving that hash update in history
goToAnchor('section1')
goToAnchor('section1', false)
// scroll to #section1, saving that hash update in history
goToAnchor('section1', true)
import { removeHash } from 'react-scrollable-anchor'
// clear URL hash
removeHash()
Please open issues on Github. Issues are easier to address if you include context and code samples.
Please contribute!
Feel free to contact me at [email protected].