Skip to content

Instantly share code, notes, and snippets.

@timilsinabishal
Created October 26, 2018 09:45
Show Gist options
  • Save timilsinabishal/a6d6d7171050f290258e27c3fca85105 to your computer and use it in GitHub Desktop.
Save timilsinabishal/a6d6d7171050f290258e27c3fca85105 to your computer and use it in GitHub Desktop.
Infinite scrolling component for react
import React from 'react';
import PropTypes from 'prop-types';
import { throttle } from 'lodash';
const propTypes = {
loading: PropTypes.bool,
loadingComponent: PropTypes.oneOfType([PropTypes.node, PropTypes.element]),
disableRefresh: PropTypes.bool,
children: PropTypes.oneOfType([PropTypes.node, PropTypes.element]).isRequired,
onEndReached: PropTypes.func.isRequired,
onEndReachedThreshold: PropTypes.number,
};
const defaultProps = {
loading: false,
loadingComponent: (
<p>Loading</p>
),
disableRefresh: false,
onEndReachedThreshold: 50,
};
export default class InfiniteScroll extends React.PureComponent {
static propTypes = propTypes;
static defaultProps = defaultProps;
componentDidMount() {
this.el = this.props.children.ref.current;
this.el.addEventListener('scroll', this.onScroll, false);
}
componentWillUnmount() {
this.el.removeEventListener('scroll', this.onScroll, false);
}
onScroll = throttle(() => {
const { disableRefresh, loading, onEndReached, onEndReachedThreshold } = this.props;
if (
(this.el.clientHeight + this.el.scrollTop) >=
(this.el.scrollHeight - onEndReachedThreshold) &&
!disableRefresh &&
!loading
) {
onEndReached();
}
}, 200)
render() {
const { children, loadingComponent, loading } = this.props;
return (
<React.Fragment>
{children}
{
loading && loadingComponent
}
</React.Fragment>);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment