Created
October 26, 2018 09:45
-
-
Save timilsinabishal/a6d6d7171050f290258e27c3fca85105 to your computer and use it in GitHub Desktop.
Infinite scrolling component for react
This file contains 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 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