Last active
April 12, 2018 10:39
-
-
Save mattvague/6843385ad0415d12a89cbdd1ac363e28 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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