Skip to content

Instantly share code, notes, and snippets.

@AsbDaryaee
Last active October 14, 2024 19:41
Show Gist options
  • Save AsbDaryaee/adea6eddb9883fc4f438f1774aa53e60 to your computer and use it in GitHub Desktop.
Save AsbDaryaee/adea6eddb9883fc4f438f1774aa53e60 to your computer and use it in GitHub Desktop.
Basic React Pagination Component + Tailwind CSS
import { useState, useEffect } from "react";
export default function Pagination ({
totalPages,
currentPage,
handlePageChange,
text,
className = "custom-class",
pageLimit = 10, // number of pages to show at a time
}) {
const [pages, setPages] = useState([]);
useEffect(() => {
const halfLimit = Math.floor(pageLimit / 2);
let start = Math.max(1, currentPage - halfLimit);
let end = Math.min(totalPages, start + pageLimit - 1);
// Adjust start and end to always show 'pageLimit' pages
start = Math.max(1, end - pageLimit + 1);
let newPages = [];
for (let i = start; i <= end; i++) {
newPages.push(i);
}
setPages(newPages);
}, [currentPage, totalPages, pageLimit]);
return (
<div className={className}>
<ul className="pagination">
{/* Previous Button */}
<li>
{text ? (
<button
className="text-slate-600 dark:text-slate-300 prev-next-btn"
onClick={() => handlePageChange(currentPage - 1)}
disabled={currentPage === 1}
>
Previous
</button>
) : (
<button
className="text-xl leading-4 text-slate-900 dark:text-white h-6 w-6 flex items-center justify-center flex-col prev-next-btn"
onClick={() => handlePageChange(currentPage - 1)}
disabled={currentPage === 1}
>
Prev
</button>
)}
</li>
{/* Ellipsis at the start if necessary */}
{pages[0] > 1 && (
<li>
<span className="ellipsis">...</span>
</li>
)}
{/* Page Numbers */}
{pages.map((page) => (
<li key={page}>
<button
className={`${page === currentPage ? "active" : ""} page-link`}
onClick={() => handlePageChange(page)}
disabled={page === currentPage}
>
{page}
</button>
</li>
))}
{/* Ellipsis at the end if necessary */}
{pages[pages.length - 1] < totalPages && (
<li>
<span className="ellipsis">...</span>
</li>
)}
{/* Next Button */}
<li>
{text ? (
<button
onClick={() => handlePageChange(currentPage + 1)}
disabled={currentPage === totalPages}
className="text-slate-600 dark:text-slate-300 prev-next-btn"
>
Next
</button>
) : (
<button
className="text-xl leading-4 text-slate-900 dark:text-white h-6 w-6 flex items-center justify-center flex-col prev-next-btn"
onClick={() => handlePageChange(currentPage + 1)}
disabled={currentPage === totalPages}
>
Next
</button>
)}
</li>
</ul>
</div>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment