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,
use the same ref in the wrapper div of the list.
To detect the last element,
we should create an onScroll
method as given below.
Add pagination to the infinite scroll
To add pagination, we will maintain following states-
For fetching the list, we will take help from fake API
To know if the response list is empty, we will use following code-
If the list is not empty, we will add the response list to the current list.
keeping it all in useEffect would look like this,
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.