How to create Pagination Component in Reactjs
To create a pagination component in React, you will need to use React’s useState
hook to keep track of the current page. Then, you can use a combination of a for
loop and a .map()
function to generate the necessary page links. Here is an example of how you might implement this:
import React, { useState } from 'react';
const Pagination = ({ numPages }) => {
const [currentPage, setCurrentPage] = useState(1);
const pageLinks = [];
for (let i = 1; i <= numPages; i++) {
pageLinks.push(
<a
key={i}
href="#"
onClick={() => setCurrentPage(i)}
className={i === currentPage ? 'active' : ''}
>
{i}
</a>
);
}
return (
<div className="pagination">
{pageLinks.map(link => link)}
</div>
);
};
In this, the Pagination
component takes in the numPages
prop, which is the total number of pages. It then generates a page link for each page, with the current page marked as "active". When a page link is clicked, the setCurrentPage
function is called to update the current page.
Note that this is just one way to implement pagination in React, and you may want to adjust the code to fit your specific needs.