To paginate a page, a general algorithm needs to be followed. Also, you should have the following variables in place:
- Total items availabe or Items count
(It can be a list of patients, books, etc coming from the database)
- Number of items to display per page or Page size
- Page count or number of pagination buttons to be rendered (**NB:**This needs to be calculated)
Calculation: Now once you know the total items available as well as the number of items to display per page or page size, we can go ahead to calculate the number of pages we can have(page1, page2, page3, etc).
So page count is calculated as :
const pageCount = Math.ceil(itemsCount/pageSize);
Paginate the data
To paginate the data on the page, we need to have access to three things. The total items, pageNumber, pageSize. Using loadash,
function paginate(items, pageNumber, pageSize) {
// get the starting index
const startIndex = (pageNumber - 1) * pageSize;
// slice data from items based on the starting index
_.(items).slice(items, startIndex).take(pageSize).value();
}