Skip to content

Instantly share code, notes, and snippets.

@jrson83
Forked from marcosdeaguiar/paginationhook.ts
Created September 21, 2023 16:28
Show Gist options
  • Save jrson83/9ba99ecc8369192543b9d93611e5a515 to your computer and use it in GitHub Desktop.
Save jrson83/9ba99ecc8369192543b9d93611e5a515 to your computer and use it in GitHub Desktop.
import * as React from "react";
const displayItem = (currentPage: number, maxPerPage: number, index:number): boolean => {
const currentPageStart = ((currentPage - 1) * maxPerPage) + 1;
const currentPageEnd = currentPage * maxPerPage;
if ((index + 1) >= currentPageStart && (index + 1) <= currentPageEnd ) {
return true;
}
return false;
}
export const usePagination = (itemList: any[], maxItemsPerPage: number = 10) => {
const [items, setItems] = React.useState(itemList);
const [currentPage, setCurrentPage] = React.useState(1);
const isPaginating = items.length > maxItemsPerPage;
const totalPages = Math.ceil(items.length / maxItemsPerPage);
const pageItems: any[] = items.filter((val, index) => {
if (!isPaginating) {
return true;
}
if (!displayItem(currentPage, maxItemsPerPage, index)) {
return false;
}
return true;
});
const setItemList = (items: any[]) => {
setCurrentPage(1);
setItems(items);
}
return {
setItemList,
isPaginating,
currentPage,
setCurrentPage,
pageItems,
totalPages
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment