Created
February 29, 2016 22:25
-
-
Save nkt/6ca4de4c13ede121b726 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
const React = require('react'); | |
const EventListener = require('react/lib/EventListener'); | |
const {shouldComponentUpdate} = require('react/lib/ReactComponentWithPureRenderMixin'); | |
const debounce = require('lodash/function/debounce'); | |
const InfinityScroll = React.createClass({ | |
propTypes: { | |
children: React.PropTypes.node.isRequired, | |
threshold: React.PropTypes.number.isRequired, | |
onNextPage: React.PropTypes.func.isRequired, | |
enabled: React.PropTypes.bool.isRequired | |
}, | |
getDefaultProps() { | |
return { | |
threshold: 250, | |
enabled: true | |
}; | |
}, | |
componentWillMount() { | |
this.onScroll = debounce(this.onScroll, 300); | |
}, | |
componentDidMount() { | |
this.listener = EventListener.listen(window, 'scroll', this.onScroll); | |
this.page = 0; | |
this.onScroll(); | |
}, | |
shouldComponentUpdate, | |
componentWillUnmount() { | |
this.listener.remove(); | |
}, | |
onScroll() { | |
if (!this.props.enabled) { | |
return; | |
} | |
const container = React.findDOMNode(this.refs.container); | |
const containerTopPosition = this.getElementTopPosition(container); | |
const scrollTop = this.getScrollTop(); | |
const bottomDistance = containerTopPosition + container.offsetHeight - scrollTop - window.innerHeight; | |
if (bottomDistance < this.props.threshold) { | |
this.props.onNextPage(++this.page); | |
} | |
}, | |
getScrollTop() { | |
if (window.pageYOffset) { | |
return window.pageYOffset; | |
} | |
return (document.documentElement || document.body.parentNode || document.body).scrollTop; | |
}, | |
getElementTopPosition(element) { | |
if (!element) { | |
return 0; | |
} | |
return element.offsetTop + this.getElementTopPosition(element.offsetParent); | |
}, | |
render() { | |
return ( | |
<div ref="container"> | |
{this.props.children} | |
</div> | |
); | |
} | |
}); | |
module.exports = InfinityScroll; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment