pagination-hook
Version:
React pagination hook. Create pagination in your React app
39 lines • 1.65 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const react_1 = require("react");
/**
* A simple react hook for creating simple pagination systems
* @param options Options for the pagination
* @returns pagination context
*/
function usePagination(options) {
const totalPages = (0, react_1.useMemo)(() => {
return Math.ceil(options.itemCount / options.pageSize);
}, [options.pageSize, options.itemCount]);
// Sometimes the page size passed is higher than the item count.
// For example: if item count is 12, currentPage is 1 and page size is 10
// then 1st page: [0, 10], 2nd page: [10, 12]
// ^ 12 not 20!
const pageSize = (0, react_1.useCallback)((n) => Math.min(options.itemCount, n * options.pageSize), [options.itemCount, options.pageSize]);
// Combined into one memoization because of mutual dependencies
const { startIndex, endIndex } = (0, react_1.useMemo)(() => ({
startIndex: pageSize(options.currentPage),
endIndex: pageSize(options.currentPage + 1),
}), [options.currentPage, pageSize]);
const hasNextPage = (0, react_1.useMemo)(() => {
// endIndex should never exceed options.itemCount
return endIndex < options.itemCount;
}, [endIndex, options.itemCount]);
const hasPreviousPage = (0, react_1.useMemo)(() => {
return options.currentPage !== 0;
}, [options.currentPage]);
return {
totalPages,
startIndex,
endIndex,
hasPreviousPage,
hasNextPage,
};
}
exports.default = usePagination;
//# sourceMappingURL=index.js.map