Skip to content

Instantly share code, notes, and snippets.

@andrewsuzuki
Last active September 19, 2017 01:51
Show Gist options
  • Save andrewsuzuki/85708fddff4b2cf11b28 to your computer and use it in GitHub Desktop.
Save andrewsuzuki/85708fddff4b2cf11b28 to your computer and use it in GitHub Desktop.
Infinite Scroll for React using ES6/7
import React from 'react'
function topPosition(domEl) {
if (!domEl) {
return 0
}
return domEl.offsetTop + topPosition(domEl.offsetParent)
}
class InfiniteScroll extends React.Component {
constructor() {
super()
this.boundScrollListener = ::this.scrollListener
}
static defaultProps = {
pageStart: 0,
hasMore: false,
loadMore: () => {},
threshold: 250
}
componentDidMount() {
this.pageLoaded = this.props.pageStart
this.attachScrollListener()
}
componentDidUpdate() {
this.attachScrollListener()
}
componentWillUnmount() {
this.detachScrollListener()
}
render() {
const { children, hasMore, loader } = this.props
return (
<div ref="infinite_scroll_ref">
{children}
{hasMore && (loader || InfiniteScroll._defaultLoader)}
</div>
)
}
scrollListener() {
const { threshold, loadMore } = this.props
const el = this.refs.infinite_scroll_ref
const scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop
if (topPosition(el) + el.offsetHeight - scrollTop - window.innerHeight < Number(threshold)) {
this.detachScrollListener()
// call loadMore after detachScrollListener to allow
// for non-async loadMore functions
loadMore(this.pageLoaded += 1)
}
}
attachScrollListener() {
if (!this.props.hasMore) {
return
}
window.addEventListener('scroll', this.boundScrollListener)
window.addEventListener('resize', this.boundScrollListener)
this.scrollListener()
}
detachScrollListener() {
window.removeEventListener('scroll', this.boundScrollListener)
window.removeEventListener('resize', this.boundScrollListener)
}
}
InfiniteScroll.setDefaultLoader = function(loader) {
InfiniteScroll._defaultLoader = loader
}
export default InfiniteScroll
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment