Implementing Infinite Scroll in React

Liz Zheng
2 min readNov 6, 2018

To make a long story short, I scoured the web to try to find an up to date version of an infinite scroll implementation that could work for my React Component without using the following unsupported/anti-pattern/discouraged/non-working implementations like:

  • ReactDOM.findNode ()
  • ComponentWillUpdate()
  • document.getElementById(‘someId’) (works but not ideal as it will return a null value if not found which requires further handling)
  • document.documentElement.scrollHeight (doesn’t get you the true scroll height of the child component)
  • document.documentElement.scrollTop (doesn’t change in value despite onScroll event handler being triggered)
  • Infinite Scroll Library from npm (Couldn’t get it to work on my child component)

Thus, here’s my very basic, direct implementation of the Infinite Scroll that should work for any React Component using ES6.

Good Working Solution:

import React, { Component } from "react"export default class MyComponent extends Component {

constructor(props) {
super(props);
this.myRef = React.createRef()
this.state = {
hasMore: false
page: 0,
}
}
componentDidMount() {
document.addEventListener("wheel", this.onScroll, {passive: true})
document.addEventListener("scroll", this.onScroll, {passive: true})
}

componentWillUnmount() {
document.removeEventListener("wheel", this.onScroll, false)
document.removeEventListener("scroll", this.onScroll, false)
}
onScroll = (evt) => {
if (!this.state.hasMore) {
return
}
const node = this.myRef.current
let scrollTop = node.scrollTop
let clientHeight = node.clientHeight
let scrollHeight = node.scrollHeight
let scrolledToBottom = Math.ceil(scrollTop + clientHeight) >= scrollHeight
if (scrolledToBottom) {
this.props.loadMoreStuff()
}
}
loadMoreStuff = () => {
//depending on what you need to load, fill in logic here.
let currPage = {this.state.page}+1
this.setState({
page: currPage,
hasMore: currPage < whateverNumberYouWant
})
}
render() {
return (
<div ref={this.myRef}>{items}</div>
)
}

If it’s a Child Component you probably need to load data through props, you can simply replace loadMoreStuff with a prop call that changes the state in the redux store. This write up is more for getting scrollTop and scrollHeight values from the DOM reference. Good luck :)

--

--

Liz Zheng

Product designer with a background in software engineering