usePagination
The usePagination
hook is a React hook designed to manage and track pagination state within a component.
Usage
The usePagination
hook provides values and functions to manage and navigate through paginated data.
import { usePagination } from "builderoo";
const { currentPage, totalPages, totalItems, gotoPage, urlForPage } = usePagination()
Return Values
Name | Type | Description |
---|---|---|
currentPage | number | The currently selected page number. |
totalPages | number | The total number of pages available. |
totalItems | number | The total number of items or records that are being paginated. |
gotoPage | function | A function to navigate to a specific page. Accepts a `pageNumber` as an argument and navigates to the specified page. The `pageNumber` should be an integer between 1 and `totalPages`. |
urlForPage | function | A function to get the url for a specific page number. |
⚠️
Important: urlForPage
function is only meant to be used to generate a URL for the search engines or
to have a copiable link. To actually navigate, always use the gotoPage
function as shown below.
Example
Here’s an example of how to use the usePagination
hook to manage and navigate through paginated data:
import React from 'react';
import { usePagination, useCollection, Link } from "builderoo";
import ProductItem from "../components/ProductItem";
export default function CollectionDetail() {
const collection = useCollection()
const { currentPage, totalPages, totalItems, gotoPage, urlForPage } = usePagination();
return (
<div className="paginated-list">
<h3 className="font-bold text-2xl">{collection.title}</h3>
<div className="mt-10">
<div className="grid grid-cols-4 gap-x-4 gap-y-8">
{ collection.products.map((item) => (
<ProductItem key={item._id} product={item} />
))}
</div>
</div>
<div className="pagination-controls">
<span>Page {currentPage} of {totalPages}</span>
<div>
{ currentPage > 1 && (
<Link
href={urlForPage(currentPage-1)}
onClick={(e) => gotoPage(currentPage-1, e)}
>
Previous Page
</Link>
) }
{ currentPage < totalPages - 1 && (
<Link
href={urlForPage(currentPage+1)}
onClick={(e) => gotoPage(currentPage+1, e)}
>
Next Page
</Link>
)}
</div>
</div>
</div>
);
}