To implement pagination for an HTML table in a Next.js project with Tailwind CSS, you can follow these steps:
- Create a state for the current page and the number of rows per page: You can use the
useState
hook from React to create these states. The initial value for the current page can be 1, and the initial value for the number of rows per page can be 10.
const [currentPage, setCurrentPage] = useState(1);
const [rowsPerPage, setRowsPerPage] = useState(10);
- Calculate the total number of pages: You can calculate the total number of pages by dividing the total number of rows by the number of rows per page. If there's a remainder, you add 1 to the total number of pages to account for the last page that might not be full.
const totalPages = Math.ceil(totalRows / rowsPerPage);
- Create a function to handle page changes: This function will be called when the user clicks on a page number. It will update the
currentPage
state with the new page number.
const handlePageChange = (pageNumber) => {
setCurrentPage(pageNumber);
};
- Create a function to handle changes in the number of rows per page: This function will be called when the user selects a new number from a dropdown or input field. It will update the
rowsPerPage
state with the new number.
const handleRowsPerPageChange = (event) => {
setRowsPerPage(event.target.value);
};
- Display the rows for the current page: You can use the
slice
method to get the rows for the current page. You multiply the current page number by the number of rows per page to get the starting index, and add the number of rows per page to get the ending index.
const rows = data.slice((currentPage - 1) * rowsPerPage, currentPage * rowsPerPage);
- Create the pagination controls: You can create a list of page numbers and a dropdown or input field to select the number of rows per page. You can use the
map
method to create the page numbers, and you can use aselect
element for the number of rows per page.
<div>
{Array.from({ length: totalPages }, (_, i) => i + 1).map((pageNumber) => (
<button onClick={() => handlePageChange(pageNumber)}>{pageNumber}</button>
))}
<select onChange={handleRowsPerPageChange}>
{[10, 20, 30, 40, 50].map((option) => (
<option value={option}>{option}</option>
))}
</select>
</div>
7. Style the pagination controls with Tailwind CSS(optional, but I'm using it here): You can use Tailwind CSS classes to style the pagination controls. For example, you can use the bg-blue-500
class to set the background color of the page buttons, and the text-white
class to set the text color.
<button className="bg-blue-500 text-white" onClick={() => handlePageChange(pageNumber)}>{pageNumber}</button>
This is a basic implementation of pagination for an HTML table in a Next.js project (with Tailwind CSS). You might need to adjust it according to your specific needs.