Created
September 11, 2018 06:25
-
-
Save RabidFire/d4dcefa564d6ddb617dff27d617470bd to your computer and use it in GitHub Desktop.
Nifty Anchor Scrolling React HOC
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import jump from 'jump.js' | |
import React, { Component } from 'react' | |
function withAnchorScroll(WrappedComponent) { | |
return class ScrollToAnchors extends Component { | |
componentDidMount() { | |
const { location: { hash } } = this.props | |
if (hash) { | |
/* | |
setTimeout is used to prevent BrowserRouter(react-router-dom) | |
from resetting the scroll back to the position on page refresh. | |
*/ | |
setTimeout(() => { | |
this.scrollToAnchor(hash) | |
}, 0) | |
} | |
} | |
componentDidUpdate({ location: prevLocation }) { | |
const { location } = this.props | |
if (location !== prevLocation) { | |
this.scrollToAnchor(location.hash) | |
} | |
} | |
scrollToAnchor = (anchor) => { | |
if (!anchor) { | |
return | |
} | |
const element = document.querySelector(anchor) | |
if (element) { | |
jump(element, { duration: 500 }) | |
} | |
} | |
render() { | |
return <WrappedComponent {...this.props} /> | |
} | |
} | |
} | |
export default withAnchorScroll |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment