It enhances user experience by efficiently managing large datasets.
Let's see how to create a custom pagination component:
State Management: Utilize React's useState to manage the current page and items per page.
const [currentPage, setCurrentPage] = useState(1);
const itemsPerPage = 10;
Calculate Total Pages: Determine the total number of pages based on the dataset length.
const totalPages = Math.ceil(data.length / itemsPerPage);
Paginate Data: Extract the subset of data corresponding to the current page.
const indexOfLastItem = currentPage * itemsPerPage;
const indexOfFirstItem = indexOfLastItem - itemsPerPage;
const currentItems = data.slice(indexOfFirstItem, indexOfLastItem);
Handle Page Changes: Create functions to navigate between pages.
const handleNextPage = () => {
setCurrentPage((prev) => Math.min(prev + 1, totalPages));
};
const handlePrevPage = () => {
setCurrentPage((prev) => Math.max(prev - 1, 1));
};
Render Pagination Controls: Display buttons or links for page navigation.
<button onClick={handlePrevPage} disabled={currentPage === 1}>
Previous
</button>
<span>{currentPage} of {totalPages}</span>
<button onClick={handleNextPage} disabled={currentPage === totalPages}>
Next
</button>
Display Current Items: Render the data for the current page.
<ul>
{currentItems.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>