Paging in ReactJS like bootstrap with Radio
- Version
- Download 23
- File Size 0.00 KB
- Create Date November 25, 2024
- Download
Paging in ReactJS allows you to break down large data sets into smaller, more manageable chunks that users can navigate through. Here's a step-by-step guide to implement paging in React:
First, set up a React project and have some data ready to paginate. You can use a static array or fetch data from an API.
(adsbygoogle = window.adsbygoogle || []).push({});
Paging in ReactJS allows you to break down large data sets into smaller, more manageable chunks that users can navigate through. Here's a step-by-step guide to implement paging in React:
1. Basic Setup
First, set up a React project and have some data ready to paginate. You can use a static array or fetch data from an API.
2. State Management for Paging
Use React's state to manage the current page and the number of items per page.
tsx file
[code lang="javascript"]
import React, { useState } from "react";
const PaginationExample = () => {
const data = Array.from({ length: 100 }, (_, i) => `Item ${i + 1}`); // Example data
const [currentPage, setCurrentPage] = useState(1);
const itemsPerPage = 10;
// Calculate the items for the current page
const indexOfLastItem = currentPage * itemsPerPage;
const indexOfFirstItem = indexOfLastItem - itemsPerPage;
const currentItems = data.slice(indexOfFirstItem, indexOfLastItem);
const totalPages = Math.ceil(data.length / itemsPerPage);
const changePage = (pageNumber: number) => {
setCurrentPage(pageNumber);
};
return (
<div>
<h1>Pagination in React</h1>
<ul>
{currentItems.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
<div>
{Array.from({ length: totalPages }, (_, i) => (
<button
key={i + 1}
onClick={() => changePage(i + 1)}
disabled={currentPage === i + 1}
>
{i + 1}
</button>
))}
</div>
</div>
);
};
export default PaginationExample;
[/code]
Explanation
Data Division:
Calculate which items belong to the current page using slice on the data array.
itemsPerPage controls how many items to show on each page.
Page Navigation:
Buttons are dynamically created for each page.
Clicking a button updates the currentPage state.
Disabled State:
The current page button is disabled for better UX.