Hook within our list component.

Hook within our list component.

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

Subscribe to get the latest posts sent to your email.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *

Blue Captcha Image
Refresh

*

To respond on your own website, enter the URL of your response which should contain a link to this post's permalink URL. Your response will then appear (possibly after moderation) on this page. Want to update or remove your response? Update or delete your post and re-enter your post's URL again. (Find out more about Webmentions.)