Skip to content

Instantly share code, notes, and snippets.

@dcortesnet
Created March 17, 2023 12:48
Show Gist options
  • Select an option

  • Save dcortesnet/cc4c29e14324814900c663de0d0741b1 to your computer and use it in GitHub Desktop.

Select an option

Save dcortesnet/cc4c29e14324814900c663de0d0741b1 to your computer and use it in GitHub Desktop.
Nextjs pagination example
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