DEV Community

Cover image for How to setup Infinite Scroll in your react component?
Ritik Banger
Ritik Banger

Posted on

How to setup Infinite Scroll in your react component?

Infinite scroll is the thing of today. Unlike pagination with pages, people prefer scrolling infinitely to get more and more data, Facebook and Instagram are very fine example leveraging the power of Infinite Scroll.

Image description

I have come across an infinite scroll package which is quite popular and many developers across the world are using this fine npm package in their web apps.

This npm package is of small size, i.e., 177kb. It takes a few props, which are as follows:

  1. The first prop is dataLength which is the length of the data.
  2. After dataLength, we have the next prop. This is one of the most important prop, We pass a loadMoreData function to it that triggers some action which fetches the next data. This fetched data is passed as children to the InfiniteScroll component, and note that the data should contain previous data too. So, it is basically, [newData, ...PreviousData]
  3. The third prop is hasMore, it is clear by its name that it takes a boolean value and tells InfiniteScroll whether to call next function on reaching the bottom or shows an endMessage to the user if next is not called i.e., hasMore is false.
  4. The fourth prop, loader takes an element which is shown as a fallback to show while the component waits for the next load of data.
  5. The fifth prop is endMessage, which tells the user that there is no more data and hasMore is false.

You can check out a codesandbox illustrating InfiniteScroll here.

Don't forget to give your data as children in between the opening and closing tag of InfiniteScroll.

    <p style={{ textAlign: 'center' }}>
      <b>You have seen all the data</b>
Enter fullscreen mode Exit fullscreen mode

There are few other props too that are useful in different scenarios but the above five props are sufficient to have a cool infinite scroll on board.

Note: If you are working with InfiniteScroll inside a popup or a modal, then ScrollableTarget prop would help. You need to create a parent div of InfiniteScroll with an id attribute and give this id as an argument to ScrollableTarget prop. A codesandbox is available here.

If you came across any other Infinite Scroll package then do mention it in the discussion and I would be happy to give it a try.

Discussion (0)