Convert Figma logo to code with AI

ankeetmaini logoreact-infinite-scroll-component

An awesome Infinite Scroll component in react.

2,843
320
2,843
193

Top Related Projects

React components for efficiently rendering large lists and tabular data

React components for efficiently rendering large lists and tabular data

The most powerful virtual list component for React

5,365

🤖 Headless UI for Virtualizing Large Element Lists in JS/TS, React, Solid, Vue and Svelte

:scroll: A versatile infinite scroll React component.

Simple React Component That Makes Titles More Readable

Quick Overview

React-infinite-scroll-component is a lightweight and easy-to-use React component that implements infinite scrolling functionality. It automatically loads more content as the user scrolls down the page, providing a seamless and efficient way to handle large datasets in React applications.

Pros

  • Simple to implement and integrate into existing React projects
  • Supports both window and scrollable element infinite scrolling
  • Customizable loading and end messages
  • Handles both vertical and horizontal scrolling

Cons

  • Limited built-in styling options
  • May require additional optimization for very large datasets
  • Documentation could be more comprehensive
  • Lacks advanced features like virtualization for extremely long lists

Code Examples

  1. Basic usage with an array of items:
import InfiniteScroll from 'react-infinite-scroll-component';

function App() {
  const [items, setItems] = useState(Array.from({ length: 20 }));
  const [hasMore, setHasMore] = useState(true);

  const fetchMoreData = () => {
    if (items.length >= 500) {
      setHasMore(false);
      return;
    }
    setTimeout(() => {
      setItems(items.concat(Array.from({ length: 20 })));
    }, 500);
  };

  return (
    <InfiniteScroll
      dataLength={items.length}
      next={fetchMoreData}
      hasMore={hasMore}
      loader={<h4>Loading...</h4>}
    >
      {items.map((_, index) => (
        <div key={index}>
          div - #{index + 1}
        </div>
      ))}
    </InfiniteScroll>
  );
}
  1. Using with a scrollable element:
<div id="scrollableDiv" style={{ height: 300, overflow: "auto" }}>
  <InfiniteScroll
    dataLength={items.length}
    next={fetchMoreData}
    hasMore={hasMore}
    loader={<h4>Loading...</h4>}
    scrollableTarget="scrollableDiv"
  >
    {items.map((item, index) => (
      <div key={index}>{item}</div>
    ))}
  </InfiniteScroll>
</div>
  1. Customizing end message:
<InfiniteScroll
  dataLength={items.length}
  next={fetchMoreData}
  hasMore={hasMore}
  loader={<h4>Loading...</h4>}
  endMessage={
    <p style={{ textAlign: 'center' }}>
      <b>Yay! You have seen it all</b>
    </p>
  }
>
  {items.map((item, index) => (
    <div key={index}>{item}</div>
  ))}
</InfiniteScroll>

Getting Started

  1. Install the package:

    npm install react-infinite-scroll-component
    
  2. Import and use the component in your React application:

    import InfiniteScroll from 'react-infinite-scroll-component';
    
    function MyComponent() {
      // ... state and data fetching logic
    
      return (
        <InfiniteScroll
          dataLength={items.length}
          next={fetchMoreData}
          hasMore={hasMore}
          loader={<h4>Loading...</h4>}
        >
          {items.map((item, index) => (
            <div key={index}>{item}</div>
          ))}
        </InfiniteScroll>
      );
    }
    
  3. Implement the fetchMoreData function to load more items when the user scrolls.

Competitor Comparisons

React components for efficiently rendering large lists and tabular data

Pros of react-window

  • Highly performant for rendering large lists and grids
  • Supports both fixed and variable size items
  • Smaller bundle size and lower memory usage

Cons of react-window

  • Steeper learning curve and more complex API
  • Less out-of-the-box functionality (e.g., no built-in infinite loading)
  • Requires more manual configuration for advanced use cases

Code Comparison

react-infinite-scroll-component:

<InfiniteScroll
  dataLength={items.length}
  next={fetchMoreData}
  hasMore={hasMore}
  loader={<h4>Loading...</h4>}
>
  {items.map((item) => (
    <div key={item.id}>{item.name}</div>
  ))}
</InfiniteScroll>

react-window:

<List
  height={400}
  itemCount={items.length}
  itemSize={35}
  width={300}
>
  {({ index, style }) => (
    <div style={style}>{items[index].name}</div>
  )}
</List>

react-infinite-scroll-component offers a simpler API with built-in infinite loading, while react-window provides more fine-grained control over rendering and better performance for large datasets. The choice between the two depends on the specific requirements of your project, such as list size, performance needs, and desired features.

React components for efficiently rendering large lists and tabular data

Pros of react-virtualized

  • More comprehensive solution for rendering large lists and tabular data
  • Offers additional components like Grid, Table, and WindowScroller
  • Better performance for very large datasets due to virtualization

Cons of react-virtualized

  • Steeper learning curve due to more complex API
  • Requires more setup and configuration
  • Larger bundle size compared to simpler infinite scroll solutions

Code Comparison

react-infinite-scroll-component:

<InfiniteScroll
  dataLength={items.length}
  next={fetchMoreData}
  hasMore={hasMore}
  loader={<h4>Loading...</h4>}
>
  {items.map((item) => (
    <div key={item.id}>{item.name}</div>
  ))}
</InfiniteScroll>

react-virtualized:

<List
  width={300}
  height={300}
  rowCount={items.length}
  rowHeight={20}
  rowRenderer={({ index, key, style }) => (
    <div key={key} style={style}>
      {items[index].name}
    </div>
  )}
/>

react-virtualized offers more control over rendering and optimization but requires more setup. react-infinite-scroll-component provides a simpler API for basic infinite scrolling needs. Choose based on your project's complexity and performance requirements.

The most powerful virtual list component for React

Pros of react-virtuoso

  • More comprehensive virtualization solution, handling both windowing and infinite scrolling
  • Better performance for large datasets due to efficient rendering of visible items
  • Supports advanced features like grouped lists and customizable scroll containers

Cons of react-virtuoso

  • Steeper learning curve due to more complex API and configuration options
  • May be overkill for simple infinite scrolling use cases
  • Requires more setup and configuration compared to react-infinite-scroll-component

Code Comparison

react-infinite-scroll-component:

<InfiniteScroll
  dataLength={items.length}
  next={fetchMoreData}
  hasMore={hasMore}
  loader={<h4>Loading...</h4>}
>
  {items.map((item) => (
    <div key={item.id}>{item.name}</div>
  ))}
</InfiniteScroll>

react-virtuoso:

<Virtuoso
  style={{ height: '400px' }}
  totalCount={items.length}
  itemContent={(index) => <div>{items[index].name}</div>}
  endReached={loadMore}
  overscan={200}
/>

react-virtuoso offers more control over rendering and performance optimization, while react-infinite-scroll-component provides a simpler API for basic infinite scrolling functionality. The choice between the two depends on the specific requirements of your project and the complexity of your list rendering needs.

5,365

🤖 Headless UI for Virtualizing Large Element Lists in JS/TS, React, Solid, Vue and Svelte

Pros of virtual

  • More flexible and powerful, supporting both infinite scrolling and virtual lists
  • Better performance for large datasets due to virtualization
  • Framework-agnostic, can be used with React, Vue, or vanilla JavaScript

Cons of virtual

  • Steeper learning curve and more complex setup
  • Requires more configuration and customization for specific use cases
  • May be overkill for simple infinite scrolling scenarios

Code Comparison

react-infinite-scroll-component:

<InfiniteScroll
  dataLength={items.length}
  next={fetchMoreData}
  hasMore={hasMore}
  loader={<h4>Loading...</h4>}
>
  {items.map((item) => (
    <div key={item.id}>{item.name}</div>
  ))}
</InfiniteScroll>

virtual:

const virtualizer = useVirtualizer({
  count: items.length,
  getScrollElement: () => parentRef.current,
  estimateSize: () => 35,
});

return (
  <div ref={parentRef}>
    <div style={{ height: `${virtualizer.getTotalSize()}px` }}>
      {virtualizer.getVirtualItems().map((virtualItem) => (
        <div key={virtualItem.key}>{items[virtualItem.index].name}</div>
      ))}
    </div>
  </div>
);

Summary

react-infinite-scroll-component is simpler to use and ideal for basic infinite scrolling needs. virtual offers more advanced features and better performance for complex scenarios, but requires more setup and configuration. Choose based on your project's specific requirements and complexity.

:scroll: A versatile infinite scroll React component.

Pros of react-list

  • More flexible and customizable for complex list rendering scenarios
  • Supports both fixed and variable height items
  • Smaller bundle size, potentially better performance for large lists

Cons of react-list

  • Less straightforward implementation for simple infinite scrolling
  • Requires more manual configuration for loading states and error handling
  • May have a steeper learning curve for beginners

Code Comparison

react-infinite-scroll-component:

<InfiniteScroll
  dataLength={items.length}
  next={fetchMoreData}
  hasMore={hasMore}
  loader={<h4>Loading...</h4>}
>
  {items.map((item) => (
    <div key={item.id}>{item.title}</div>
  ))}
</InfiniteScroll>

react-list:

<ReactList
  itemRenderer={(index, key) => (
    <div key={key}>{items[index].title}</div>
  )}
  length={items.length}
  type='uniform'
/>

The react-infinite-scroll-component provides a more declarative API for infinite scrolling, while react-list offers greater control over rendering and optimization. react-list requires manual implementation of loading and error states, whereas react-infinite-scroll-component includes these features out of the box. Choose based on your specific requirements and level of customization needed.

Simple React Component That Makes Titles More Readable

Pros of react-wrap-balancer

  • Focuses on text wrapping and balancing, improving readability and aesthetics
  • Lightweight and specific to text layout optimization
  • Easy to implement for headings and short text blocks

Cons of react-wrap-balancer

  • Limited in scope compared to react-infinite-scroll-component's functionality
  • May not be as useful for long-form content or dynamic lists
  • Requires additional components for scrolling or pagination features

Code Comparison

react-wrap-balancer:

import Balancer from 'react-wrap-balancer'

function Heading() {
  return <Balancer>Your balanced heading text here</Balancer>
}

react-infinite-scroll-component:

import InfiniteScroll from 'react-infinite-scroll-component'

function List() {
  return (
    <InfiniteScroll dataLength={items.length} next={fetchMoreData} hasMore={true}>
      {items.map((item) => <div key={item.id}>{item.name}</div>)}
    </InfiniteScroll>
  )
}

The code comparison highlights the different purposes of these libraries. react-wrap-balancer is used to wrap and balance text content, while react-infinite-scroll-component is designed for implementing infinite scrolling functionality in lists or content feeds. The choice between these libraries depends on the specific needs of your project, whether it's optimizing text layout or handling large datasets with continuous scrolling.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

react-infinite-scroll-component npm npm

All Contributors

A component to make all your infinite scrolling woes go away with just 4.15 kB! Pull Down to Refresh feature added. An infinite-scroll that actually works and super-simple to integrate!

Install

  npm install --save react-infinite-scroll-component

  or

  yarn add react-infinite-scroll-component

  // in code ES6
  import InfiniteScroll from 'react-infinite-scroll-component';
  // or commonjs
  var InfiniteScroll = require('react-infinite-scroll-component');

Using

<InfiniteScroll
  dataLength={items.length} //This is important field to render the next data
  next={fetchData}
  hasMore={true}
  loader={<h4>Loading...</h4>}
  endMessage={
    <p style={{ textAlign: 'center' }}>
      <b>Yay! You have seen it all</b>
    </p>
  }
  // below props only if you need pull down functionality
  refreshFunction={this.refresh}
  pullDownToRefresh
  pullDownToRefreshThreshold={50}
  pullDownToRefreshContent={
    <h3 style={{ textAlign: 'center' }}>&#8595; Pull down to refresh</h3>
  }
  releaseToRefreshContent={
    <h3 style={{ textAlign: 'center' }}>&#8593; Release to refresh</h3>
  }
>
  {items}
</InfiniteScroll>

Using scroll on top

<div
  id="scrollableDiv"
  style={{
    height: 300,
    overflow: 'auto',
    display: 'flex',
    flexDirection: 'column-reverse',
  }}
>
  {/*Put the scroll bar always on the bottom*/}
  <InfiniteScroll
    dataLength={this.state.items.length}
    next={this.fetchMoreData}
    style={{ display: 'flex', flexDirection: 'column-reverse' }} //To put endMessage and loader to the top.
    inverse={true} //
    hasMore={true}
    loader={<h4>Loading...</h4>}
    scrollableTarget="scrollableDiv"
  >
    {this.state.items.map((_, index) => (
      <div style={style} key={index}>
        div - #{index}
      </div>
    ))}
  </InfiniteScroll>
</div>

The InfiniteScroll component can be used in three ways.

  • Specify a value for the height prop if you want your scrollable content to have a specific height, providing scrollbars for scrolling your content and fetching more data.
  • If your scrollable content is being rendered within a parent element that is already providing overflow scrollbars, you can set the scrollableTarget prop to reference the DOM element and use it's scrollbars for fetching more data.
  • Without setting either the height or scrollableTarget props, the scroll will happen at document.body like Facebook's timeline scroll.

docs version wise

3.0.2

live examples

  • infinite scroll (never ending) example using react (body/window scroll)
    • Edit yk7637p62z
  • infinte scroll till 500 elements (body/window scroll)
    • Edit 439v8rmqm0
  • infinite scroll in an element (div of height 400px)
    • Edit w3w89k7x8
  • infinite scroll with scrollableTarget (a parent element which is scrollable)
    • Edit r7rp40n0zm

props

nametypedescription
nextfunctiona function which must be called after reaching the bottom. It must trigger some sort of action which fetches the next data. The data is passed as children to the InfiniteScroll component and the data should contain previous items too. e.g. Initial data = [1, 2, 3] and then next load of data should be [1, 2, 3, 4, 5, 6].
hasMorebooleanit tells the InfiniteScroll component on whether to call next function on reaching the bottom and shows an endMessage to the user
childrennode (list)the data items which you need to scroll.
dataLengthnumberset the length of the data.This will unlock the subsequent calls to next.
loadernodeyou can send a loader component to show while the component waits for the next load of data. e.g. <h3>Loading...</h3> or any fancy loader element
scrollThresholdnumber | stringA threshold value defining when InfiniteScroll will call next. Default value is 0.8. It means the next will be called when user comes below 80% of the total height. If you pass threshold in pixels (scrollThreshold="200px"), next will be called once you scroll at least (100% - scrollThreshold) pixels down.
onScrollfunctiona function that will listen to the scroll event on the scrolling container. Note that the scroll event is throttled, so you may not receive as many events as you would expect.
endMessagenodethis message is shown to the user when he has seen all the records which means he's at the bottom and hasMore is false
classNamestringadd any custom class you want
styleobjectany style which you want to override
heightnumberoptional, give only if you want to have a fixed height scrolling content
scrollableTargetnode or stringoptional, reference to a (parent) DOM element that is already providing overflow scrollbars to the InfiniteScroll component. You should provide the id of the DOM node preferably.
hasChildrenboolchildren is by default assumed to be of type array and it's length is used to determine if loader needs to be shown or not, if your children is not an array, specify this prop to tell if your items are 0 or more.
pullDownToRefreshboolto enable Pull Down to Refresh feature
pullDownToRefreshContentnodeany JSX that you want to show the user, default={<h3>Pull down to refresh</h3>}
releaseToRefreshContentnodeany JSX that you want to show the user, default={<h3>Release to refresh</h3>}
pullDownToRefreshThresholdnumberminimum distance the user needs to pull down to trigger the refresh, default=100px , a lower value may be needed to trigger the refresh depending your users browser.
refreshFunctionfunctionthis function will be called, it should return the fresh data that you want to show the user
initialScrollYnumberset a scroll y position for the component to render with.
inverseboolset infinite scroll on top

Contributors ✨

Thanks goes to these wonderful people (emoji key):


Ankeet Maini

💬 📖 💻 👀 🚧

Darsh Shah

🚇

This project follows the all-contributors specification. Contributions of any kind are welcome!

LICENSE

MIT

NPM DownloadsLast 30 Days