Created
October 11, 2021 04:48
-
-
Save IBRAHIMDANS/38727aaa25e0098361f85af570cd30da to your computer and use it in GitHub Desktop.
hooks usePagination
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"; | |
const usePagination: UsePagination = ({ contentPerPage, count }) => { | |
const [page, setPage] = useState(1); | |
// number of pages in total (total items / content on each page) | |
const pageCount = Math.ceil(count / contentPerPage); | |
// index of last item of current page | |
const lastContentIndex = page * contentPerPage; | |
// index of first item of current page | |
const firstContentIndex = lastContentIndex - contentPerPage; | |
// change page based on direction either front or back | |
const changePage = (direction: boolean) => { | |
setPage((state) => { | |
// move forward | |
if (direction) { | |
// if page is the last page, do nothing | |
if (state === pageCount) { | |
return state; | |
} | |
return state + 1; | |
// go back | |
} else { | |
// if page is the first page, do nothing | |
if (state === 1) { | |
return state; | |
} | |
return state - 1; | |
} | |
}); | |
}; | |
const setPageSAFE = (num: number) => { | |
// if number is greater than number of pages, set to last page | |
if (num > pageCount) { | |
setPage(pageCount); | |
// if number is less than 1, set page to first page | |
} else if (num < 1) { | |
setPage(1); | |
} else { | |
setPage(num); | |
} | |
}; | |
return { | |
totalPages: pageCount, | |
nextPage: () => changePage(true), | |
prevPage: () => changePage(false), | |
setPage: setPageSAFE, | |
firstContentIndex, | |
lastContentIndex, | |
page, | |
}; | |
}; | |
export default usePagination; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment