How to Add Infinite Scroll in React.js

Trending 4 days ago

Have you ever travel crossed a website aliases app that loads and displays much contented arsenic you scroll? This is what we telephone infinite scroll.

Infinite scroll is simply a celebrated method that tin make it easier to browse ample amounts of content. It tin besides make for a smoother personification experience, particularly connected mobile devices.

You tin instrumentality infinite scroll successful React successful a fewer different ways. The first is to usage a room for illustration react-infinite-scroll-component. This library’s constituent triggers an arena whenever nan personification scrolls to nan bottommost of nan page. You tin past usage this arena arsenic a cue to load much content.

Another measurement to instrumentality infinite scroll successful React is via its built-in functions. One specified usability is “componentDidMount,” which React calls erstwhile it first mounts a component.

You tin usage this usability to load nan first batch of data, followed by nan “componentDidUpdate” usability to load consequent information arsenic nan personification scrolls down.

You tin besides use React hooks to adhd an infinite scrolling feature.

Using nan react-infinite-scroll-component Library

There are a fewer ways to usage nan react-infinite-scroll-component.

Install react-infinite-scroll-component

To kickstart nan usage, you first request to instal it via npm:

npm instal react-infinite-scroll-component --save

Import react-infinite-scroll-component into React

After installation, you request to import nan infinite scroll room into your React component.

import React from 'react'
import InfiniteScroll from 'react-infinite-scroll-component'
 
class App extends React.Component {
  constructor() {
    super()
    this.state = {
      items: [],
      hasMore: true
    }
  }

  componentDidMount() {
    this.fetchData(1)
  }
 
  fetchData = (page) => {
    const newItems = []
 
    for (let one = 0; one < 100; i++) {
      newItems.push(i )
    }
 
    if (page === 100) {
      this.setState({ hasMore: false })
    }
 
    this.setState({ items: [...this.state.items, ...newItems] })
  }
 
  render() {
    return (
      <div>
        <h1>Infinite Scroll</h1>
        <InfiniteScroll
          dataLength={this.state.items.length}
          next={this.fetchData}
          hasMore={this.state.hasMore}
          loader={<h4>Loading...</h4>}
          endMessage={
            <p style={{ textAlign: 'center' }}>
              <b>Yay! You person seen it all</b>
            </p>
          }
        >
          {this.state.items.map((item, index) => (
            <div key={index}>
              {item}
            </div>
          ))}
        </InfiniteScroll>
      </div>
    )
  }
}
 
export default App

This codification starts by importing React and nan InfiniteScroll constituent from nan react-infinite-scroll-component library. It past creates a stateful constituent and initializes it pinch an quiet items array and a hasMore emblem group to True.

Set Parameters

In nan componentDidMount lifecycle method, you must telephone nan fetchData method pinch a page parameter group to 1. The fetchData method makes an API telephone to fetch data. This react-infinite-scroller illustration generates immoderate dummy information and creates an array of 100 items.

Once nan page parameter reaches 100, since nary much items exist, you tin group nan hasMore emblem to False. This stops nan InfiniteScroll constituent from making further API calls. Finally, group nan authorities utilizing nan caller data.

The render method uses nan InfiniteScroll constituent and passes successful immoderate props. The dataLength prop is group to nan magnitude of nan items array. The pursuing prop is group to nan fetchData method. The hasMore prop is group adjacent to nan hasMore flag.

The loader prop causes nan constituent to render its contents arsenic a loading indicator. Likewise, it will render nan endMessage prop arsenic a connection erstwhile each nan information has vanished loading.

You tin walk different props to nan InfiniteScroll component, but these are nan ones you'll usage astir often.

react app pinch infinite scroll utilizing 3rd statement packages

Using Built-In Functions

React besides has immoderate built-in methods that you tin usage to instrumentality InfiniteScroll.

The first method is componentDidUpdate. React calls this method aft it updates a component. You tin usage this method to cheque if nan personification has scrolled to nan bottommost of nan page. If yes, it loads much data.

The 2nd method is scroll, which React calls erstwhile nan personification scrolls. You tin usage this method to support way of nan scroll position. You tin load much information if nan personification has scrolled to nan bottommost of nan page.

Here's a React infinite scroll illustration that shows you really to usage these methods:

import React, {useState, useEffect} from 'react'
 
function App() {
  const [items, setItems] = useState([])
  const [hasMore, setHasMore] = useState(true)
  const [page, setPage] = useState(1)
 
  useEffect(() => {
    fetchData(page)
  }, [page])
 
  const fetchData = (page) => {
    const newItems = []
 
    for (let one = 0; one < 100; i++) {
      newItems.push(i)
    }
 
    if (page === 100) {
      setHasMore(false)
    }
 
    setItems([...items, ...newItems])
  }
 
  const onScroll = () => {
    const scrollTop = document.documentElement.scrollTop
    const scrollHeight = document.documentElement.scrollHeight
    const clientHeight = document.documentElement.clientHeight
 
    if (scrollTop + clientHeight >= scrollHeight) {
      setPage(page + 1)
    }
  }
 
  useEffect(() => {
    window.addEventListener('scroll', onScroll)
    return () => window.removeEventListener('scroll', onScroll)
  }, [items])
 
  return (
    <div>
      {items.map((item, index) => (
        <div key={index}>
          {item}
        </div>
      ))}
    </div>
  )
}
 
export default App

This codification uses nan useState and useEffect hooks to negociate authorities and broadside effects.

Within nan useEffect hook, it calls nan fetchData method pinch nan existent page. The fetchData method makes an API telephone to fetch data. In this example, you're conscionable generating immoderate dummy information to show nan technique.

The for loop populates nan newItems array pinch 100 integers. If nan page parameter is 100, it sets nan hasMore emblem to False. This stops nan infinite scroll constituent from making further API calls.

Finally, group nan authorities pinch nan caller data.

The onScroll method keeps way of nan scroll position. You tin load much information if nan personification scrolls to nan page's bottom.

The useEffect hook adds an arena listener for nan scroll event. When nan scroll arena fires, it calls nan onScroll method.

react app surface pinch infinite scroll utilizing in-built features

There are pros and cons to utilizing React's infinite scroll. It improves nan personification interface, making for a smoother experience, particularly connected mobile devices. However, it tin besides lead to users missing contented arsenic they whitethorn not scroll down acold capable to spot it.

It is basal to measurement up nan pros and cons of nan infinite scroll technique earlier implementing it connected your website aliases app.

Improve User Experience With Infinite Scroll successful React.js

Adding infinite scroll to your React.js website aliases app tin amended nan personification experience. With infinite scroll, users don't person to click to spot much content. Using Infinite Scroll successful your React.js app tin trim nan number of page loads, which further improves performance.

You tin besides easy deploy your React app to Github pages for free.

Source Tutorials
Tutorials