How to make pagination using tailwind css in react project
To create pagination using Tailwind CSS in a React project, you can follow these steps:
Create a new component for the pagination, for example,
Pagination.jsin your React project.Define the structure of the pagination using JSX. For example, you can use a
ulelement to create a list of pages and alielement for each page. You can also add a "previous" and "next" button for navigation.Apply the Tailwind CSS classes to the elements in the JSX to style the pagination. For example, you can use the
flexclass to align the pages horizontally, and thetext-centerclass to center the text. You can also use thebg-gray-200class to set the background color of the pages, and thep-2class to add padding.Add functionality to the pagination component to handle page changes. For example, you can use a state variable to keep track of the current page, and use event handlers to update the state when the "previous" or "next" buttons are clicked.
Use the
Paginationcomponent in your main component and pass the necessary props like total number of pages and current page.
Here's an example of what the JSX for a pagination component might look like, using Tailwind CSS classes:
import React, { useState } from "react";
const Pagination = ({totalPages, currentPage}) => {
const [currentPage, setCurrentPage] = useState(currentPage);
const handleNextClick = () => {
if (currentPage < totalPages) {
setCurrentPage(currentPage + 1);
}
};
const handlePrevClick = () => {
if (currentPage > 1) {
setCurrentPage(currentPage - 1);
}
};
return (
<div className="flex justify-center">
<button
className="bg-gray-300 hover:bg-gray-400 text-gray-800 font-bold py-2 px-4 rounded-l"
onClick={handlePrevClick}
disabled={currentPage === 1}
>
Previous
</button>
<ul className="flex">
{Array.from({ length: totalPages }, (_, i) => (
<li
key={i}
className={`bg-gray-200 text-center p-2 m-2 rounded-full ${
i + 1 === currentPage ? "text-white bg-blue-500" : ""
}`}
>
{i + 1}
</li>
))}
</ul>
<button
className="bg-gray-300 hover:bg-gray-400 text-gray-800 font-bold py-2 px-4 rounded-r"
onClick={handleNextClick}
disabled={currentPage === totalPages}
>
Next
</button>
</div>
);
};
export default Pagination;
This is just an example and can be customized according to the project needs.
Please note that these are general instructions and may vary depending on the specific requirements of your project.
Post a Comment