Created
December 13, 2020 14:51
-
-
Save mamadOuologuem/561163ac2e4630c89dae4cf72e2fdddc to your computer and use it in GitHub Desktop.
Hooks for pagination in React with a given window view
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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