Skip to content

Instantly share code, notes, and snippets.

@mattvague
Last active April 12, 2018 10:39
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattvague/6843385ad0415d12a89cbdd1ac363e28 to your computer and use it in GitHub Desktop.
Save mattvague/6843385ad0415d12a89cbdd1ac363e28 to your computer and use it in GitHub Desktop.
import React from 'react'
import { PureComponent } from 'react'
class ScrollVelocity extends PureComponent {
constructor (props, context) {
super(props, context)
this.state = {
lastScrollTop: 0,
lastScrollLeft: 0,
velocityY: 0.0,
velocityX: 0.0,
lastUpdatedAt: null
}
this._onScroll = this._onScroll.bind(this)
}
render () {
const { children } = this.props
const { velocityX, velocityY } = this.state
return children({ velocityX, velocityY, onScroll: this._onScroll })
}
_onScroll ({ scrollLeft, scrollTop }) {
const now = Date.now()
const deltaT = (now - this.state.lastUpdatedAt)
const deltaY = scrollTop - this.state.lastScrollTop
const deltaX = scrollLeft - this.state.lastScrollLeft
const velocityX = Math.round(deltaX / deltaT)
const velocityY = Math.round(deltaY / deltaT)
this.setState({
velocityX, velocityY,
lastScrollTop: scrollTop,
lastScrollLeft: scrollLeft,
lastUpdatedAt: now
})
}
}
ScrollVelocity.propTypes = {
children: React.PropTypes.func.isRequired
}
export default ScrollVelocity
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment