To implement pagination for a list of blog articles in a React functional component, you can follow these steps:
- Define state variables to keep track of the current page and the number of items per page. You can do this using the useState hook, like so:
- Calculate the total number of pages based on the number of items and the number of items per page. You can do this using the Math.ceil function, like so:
- Define a function to handle the page change. This function will update the current page in the state.
- Use the slice method to display only the items for the current page. You can calculate the starting and ending indexes based on the current page and the number of items per page.
- Render the displayed items and a pagination component that allows the user to navigate to different pages. You can use the map method to generate the pagination links.
const [currentPage, setCurrentPage] = useState(1);
const [itemsPerPage, setItemsPerPage] = useState(10);
const totalPages = Math.ceil(items.length / itemsPerPage);
const handlePageChange = (pageNumber) => {
setCurrentPage(pageNumber);
};
const startIndex = (currentPage - 1) * itemsPerPage;
const endIndex = startIndex + itemsPerPage;
const displayedItems = items.slice(startIndex, endIndex);
return (
<div>
{displayedItems.map((item) => (
// render each item here
))}
<div className="pagination">
{Array.from({ length: totalPages }, (_, i) => i + 1).map((pageNumber) => (
<a
key={pageNumber}
onClick={() => handlePageChange(pageNumber)}
className={pageNumber === currentPage ? "active" : ""}
>
{pageNumber}
</a>
))}
</div>
</div>
);
The pagination links are generated using the Array.from method to create an array with as many elements as the total number of pages. The map method is used to render each link as an anchor element. The className prop is used to apply the "active" class to the current page link. Finally, the onClick handler calls the handlePageChange function to update the current page in the state.