Skip to content

Instantly share code, notes, and snippets.

@mamadOuologuem
Created December 13, 2020 14:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mamadOuologuem/561163ac2e4630c89dae4cf72e2fdddc to your computer and use it in GitHub Desktop.
Save mamadOuologuem/561163ac2e4630c89dae4cf72e2fdddc to your computer and use it in GitHub Desktop.
Hooks for pagination in React with a given window view
import { useState } from 'react';
import { inRange } from 'lodash';
function getSliceStartIndex(activeIndex, total, perSlice) {
const sliceStartIndex = activeIndex - Math.floor(perSlice / 2);
if (sliceStartIndex < 0) {
return 0;
}
if (sliceStartIndex > total - perSlice) {
return total - perSlice;
}
return sliceStartIndex;
}
export const usePagination = ({ total, perSlice = 1, step = 1 }) => {
const [activeIndex, setActiveIndex] = useState(0);
const sliceStartIndex = getSliceStartIndex(activeIndex, total, perSlice);
const slice = {
startIndex: sliceStartIndex,
endIndex: sliceStartIndex + perSlice - 1,
};
const hasPrev = activeIndex - step >= 0;
const hasNext = activeIndex + step < total;
function movePrev() {
if (hasPrev) {
setActiveIndex(activeIndex - step);
} else {
setActiveIndex(0);
}
}
function moveNext() {
if (hasNext) {
setActiveIndex(activeIndex + step);
} else {
setActiveIndex(total - 1);
}
}
function isVisibleIndex(index) {
return inRange(index, slice?.startIndex, slice?.endIndex + 1);
}
return {
slice,
activeIndex,
hasPrev,
hasNext,
moveNext,
movePrev,
updateActiveIndex: setActiveIndex,
isVisibleIndex,
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment