@shyann
In React.js, pagination can be implemented using various approaches. One of the common approaches is to maintain a state that tracks the current page and the number of items per page. Here is a step-by-step guide on how to paginate in React.js:
1 2 3 4 5 6 7 8 |
import React, { useState } from 'react';
const YourComponent = () => {
const [currentPage, setCurrentPage] = useState(1);
const [itemsPerPage, setItemsPerPage] = useState(10);
// rest of your component code
}
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
const YourComponent = () => {
// previous code
// Assuming items is an array containing all your items
const indexOfLastItem = currentPage * itemsPerPage;
const indexOfFirstItem = indexOfLastItem - itemsPerPage;
const currentItems = items.slice(indexOfFirstItem, indexOfLastItem);
return (
<div>
{currentItems.map(item => (
<div key={item.id}>{item.name}</div>
))}
</div>
);
};
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
const YourComponent = () => {
// previous code
const totalPages = Math.ceil(items.length / itemsPerPage);
const handlePageChange = (pageNumber) => {
setCurrentPage(pageNumber);
};
return (
<div>
{currentItems.map(item => (
<div key={item.id}>{item.name}</div>
))}
<div>
{Array.from({ length: totalPages }, (_, index) => index + 1).map(
pageNumber => (
<button
key={pageNumber}
onClick={() => handlePageChange(pageNumber)}
disabled={pageNumber === currentPage}
>
{pageNumber}
</button>
)
)}
</div>
</div>
);
};
|
That's it! With these steps, you should be able to implement pagination in React.js. Feel free to customize the code according to your specific requirements and UI design.