Skip to content

Instantly share code, notes, and snippets.

@RabidFire
Created September 11, 2018 06:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RabidFire/d4dcefa564d6ddb617dff27d617470bd to your computer and use it in GitHub Desktop.
Save RabidFire/d4dcefa564d6ddb617dff27d617470bd to your computer and use it in GitHub Desktop.
Nifty Anchor Scrolling React HOC
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