When dealing with large amounts of data in a web application, it’s essential to present that data in a user-friendly way. Pagination assists in breaking down the content into smaller chunks, which not only enhances user experience but also improves performance by loading fewer items at once. In this tutorial, we will create a basic pagination component in React, detailing the process along the way.
First, let’s set up our React project. If you haven't already created a React app, you can do so using Create React App. Open your terminal and run:
npx create-react-app react-pagination-example cd react-pagination-example
Once your app is created, navigate into your project folder.
For the purpose of this example, let’s create some sample data that we can paginate. In your src
folder, create a new file named data.js
and add the following code:
const data = Array.from({ length: 100 }, (_, index) => `Item ${index + 1}`); export default data;
This will generate an array of 100 items for us to display.
Next, we’ll create our pagination component. Inside the src
folder, create a new folder named components
and then create a file called Pagination.js
inside it. Here’s a basic structure for our pagination component:
import React from 'react'; const Pagination = ({ totalItems, itemsPerPage, currentPage, onPageChange }) => { const totalPages = Math.ceil(totalItems / itemsPerPage); const handlePageChange = (page) => { if (page !== currentPage) { onPageChange(page); } }; return ( <div className="pagination"> {[...Array(totalPages)].map((_, index) => { const page = index + 1; return ( <button key={index} onClick={() => handlePageChange(page)} disabled={currentPage === page} style={{ margin: "0 5px" }} > {page} </button> ); })} </div> ); }; export default Pagination;
Props: The Pagination component accepts four props:
totalItems
: The total number of items to paginate.itemsPerPage
: How many items should be displayed per page.currentPage
: The currently selected page.onPageChange
: A function to call when the page changes.Calculating Total Pages: The total number of pages is computed by dividing the total items by items per page.
Rendering Buttons: We create an array of buttons for each page number and render them.
Now, let’s create a main component that utilizes our Pagination
component. Open the src/App.js
file and modify it as follows:
import React, { useState } from "react"; import data from "./data"; import Pagination from "./components/Pagination"; const App = () => { const [currentPage, setCurrentPage] = useState(1); const itemsPerPage = 10; const handlePageChange = (page) => { setCurrentPage(page); }; const startIndex = (currentPage - 1) * itemsPerPage; const selectedItems = data.slice(startIndex, startIndex + itemsPerPage); return ( <div className="app"> <h1>Pagination Example</h1> <ul> {selectedItems.map((item, index) => ( <li key={index}>{item}</li> ))} </ul> <Pagination totalItems={data.length} itemsPerPage={itemsPerPage} currentPage={currentPage} onPageChange={handlePageChange} /> </div> ); }; export default App;
State Management: We use the useState
hook to keep track of the currentPage
.
Data Slicing: The selected items for the current page are sliced from the original data based on the currentPage
.
Rendering: We display the list of items and include the Pagination
component, passing in the appropriate props.
To improve the appearance of our-pagination component, let’s add some basic CSS. Open src/App.css
and add the following styles:
.pagination { margin: 20px 0; } button { padding: 10px; border: none; background-color: #007bff; color: white; cursor: pointer; } button:disabled { background-color: #d3d3d3; }
.pagination
class and buttons, enhancing user interaction with a simple color scheme and padding.Now, you can start your application with:
npm start
You should see a simple pagination in action. The items will display 10 at a time, and clicking on the page numbers updates the list accordingly.
In this blog post, we built a basic pagination component in React from scratch. We provided important context, sample data, and explanations of our code throughout the tutorial. By following these steps, you should now have a solid foundational understanding of how to create a pagination component in React. Happy coding!
14/09/2024 | ReactJS
24/08/2024 | ReactJS
24/08/2024 | ReactJS
16/07/2024 | ReactJS
14/09/2024 | ReactJS
24/08/2024 | ReactJS
24/08/2024 | ReactJS
14/09/2024 | ReactJS
25/07/2024 | ReactJS