React custom infinite scroll with pagination


There are lots of npm packages available in React to implement infinite scrolling, but it’s really fun to create and use our own infinite scroll. The best part of implementing self created infinite scroll is, we can customize it in the way we want.

So, let’s start the journey.

Need

Infinite scroll allows users to scroll through a datalist with no finishing line in sight. We can include pagination i.e.(chunk by chunk data fetching) while scrolling to increase performance of the website.

Implementation in React

To implement infinite scroll, the first thing we should know is the last element of the current list. For getting it, we can take help from the onScroll method and save our reference in react useRef.

Following code will give us an idea regarding implementation of the onScroll method and using ref.

let’s import useRef first,

  const listInnerRef = useRef();

use the same ref in the wrapper div of the list.

<div
  onScroll={onScroll}
  ref={listInnerRef}
>
  <!-- List Items -->  
</div>

To detect the last element, we should create an onScroll method as given below.

  const onScroll = () => {
    if (listInnerRef.current) {
      const { scrollTop, scrollHeight, clientHeight } = listInnerRef.current;
      if (scrollTop + clientHeight === scrollHeight) {
        // This will be triggered after hitting the last element.
        // API call should be made here while implementing pagination.
      }
    }
  };

Add pagination to the infinite scroll

To add pagination, we will maintain following states-

  const [currPage, setCurrPage] = useState(1); // storing current page number
  const [prevPage, setPrevPage] = useState(0); // storing prev page number
  const [userList, setUserList] = useState([]); // storing list
  const [wasLastList, setWasLastList] = useState(false); // setting a flag to know the last list

For fetching the list, we will take help from fake API

  const response = await axios.get(
    `https://api.instantwebtools.net/v1/passenger?page=${currPage}&size=10`
  );

To know if the response list is empty, we will use following code-

   if (!response.data.data.length) {
      setWasLastList(true);
    }

If the list is not empty, we will add the response list to the current list.

  setPrevPage(currPage);
  setUserList([...userList, ...response.data.data]);

keeping it all in useEffect would look like this,

  useEffect(() => {
    const fetchData = async () => {
      const response = await axios.get(
        `https://api.instantwebtools.net/v1/passenger?page=${currPage}&size=10`
      );
      if (!response.data.data.length) {
        setWasLastList(true);
        return;
      }
      setPrevPage(currPage);
      setUserList([...userList, ...response.data.data]);
    };
    if (!wasLastList && prevPage !== currPage) {
      fetchData();
    }
  }, [currPage, wasLastList, prevPage, userList]);

That’s it we are done to implement custom infinite scroll with pagination in our react application.

For complete code reference, click on the link react-custom-infinite-scroll-with-pagination

Advantage

  • Custom infinite scroll with pagination does improve the performance of website.

  • Though this is not a npm package we do not require to implement any third party library and customize this as per our need.

Join Our Newsletter