The usePagination hook encapsulates pagination logic.
const usePagination = (items, itemsPerPage) => {
const [currentPage, setCurrentPage] = React.useState(1);
const maxPage = Math.ceil(items.length / itemsPerPage);
const currentItems = items.slice(
(currentPage – 1) * itemsPerPage,
currentPage * itemsPerPage
);
const nextPage = () => {
setCurrentPage((prevPage) => Math.min(prevPage + 1, maxPage));
};
const prevPage = () => {
setCurrentPage((prevPage) => Math.max(prevPage – 1, 1));
};
return { currentItems, nextPage, prevPage, currentPage, maxPage };
};
const PaginatedList = ({ items, renderItem, itemsPerPage }) => {
const { currentItems, nextPage, prevPage, currentPage, maxPage } = usePagination(
items,
itemsPerPage
);
return (
<div>
<ul>
{currentItems.map((item, index) => (
<li key={index}>{renderItem(item)}</li>
))}
</ul>
<div>
<button onClick={prevPage} disabled={currentPage === 1}>
Previous
</button>
<button onClick={nextPage} disabled={currentPage === maxPage}>
Next
</button>
</div>
</div>
);
};
In this example we’ll demonstrates a paginated list where users can navigate through pages of items.
The hook handles all pagination logic, making it reusable across different components.
const App = () => {
const items = Array.from({ length: 100 }, (_, i) => `Item ${i + 1}`);
return (
<div>
<h1>Paginated List</h1>
<PaginatedList
items={items}
itemsPerPage={10}
renderItem={(item) => <div>{item}</div>}
/>
</div>
);
};
Discover more from Kvnbbg.fr
Subscribe to get the latest posts sent to your email.