Created
March 17, 2023 12:48
-
-
Save dcortesnet/cc4c29e14324814900c663de0d0741b1 to your computer and use it in GitHub Desktop.
Nextjs pagination example
This file contains hidden or 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 { AppState } from "@/redux/store"; | |
| import { useRouter } from "next/router"; | |
| import { Pagination } from "react-bootstrap"; | |
| import { useSelector } from "react-redux"; | |
| export const VersionPagination = () => { | |
| const router = useRouter(); | |
| const pagination = useSelector( | |
| (state: AppState) => state.versions.pagination | |
| ); | |
| const handleClickChoosePagination = (page: number) => { | |
| const currentPath = router.pathname; | |
| const currentQuery = router.query; | |
| currentQuery.page = String(page); | |
| router.push({ | |
| pathname: currentPath, | |
| query: currentQuery, | |
| }); | |
| }; | |
| const handleClickStartPagination = () => { | |
| const currentPath = router.pathname; | |
| const currentQuery = router.query; | |
| currentQuery.page = String(1); | |
| router.push({ | |
| pathname: currentPath, | |
| query: currentQuery, | |
| }); | |
| }; | |
| const handleClickEndPagination = () => { | |
| const currentPath = router.pathname; | |
| const currentQuery = router.query; | |
| currentQuery.page = String(pagination.pageCount); | |
| router.push({ | |
| pathname: currentPath, | |
| query: currentQuery, | |
| }); | |
| }; | |
| const getPaginationItems = () => { | |
| let items = []; | |
| for (let index = 1; index <= Number(pagination?.pageCount); index++) { | |
| if (index === pagination.page) { | |
| items.push(<Pagination.Item active>{index}</Pagination.Item>); | |
| } else { | |
| items.push( | |
| <Pagination.Item onClick={() => handleClickChoosePagination(index)}> | |
| {index} | |
| </Pagination.Item> | |
| ); | |
| } | |
| } | |
| return items; | |
| }; | |
| return ( | |
| <Pagination className="d-flex justify-content-center"> | |
| <Pagination.First onClick={() => handleClickStartPagination()} /> | |
| {getPaginationItems()} | |
| <Pagination.Last onClick={() => handleClickEndPagination()} /> | |
| </Pagination> | |
| ); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment