Skip to content

Instantly share code, notes, and snippets.

@nkt
Created February 29, 2016 22: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 nkt/6ca4de4c13ede121b726 to your computer and use it in GitHub Desktop.
Save nkt/6ca4de4c13ede121b726 to your computer and use it in GitHub Desktop.
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