logologo
  • AI Tools

    DB Query GeneratorMock InterviewResume BuilderLearning Path GeneratorCheatsheet GeneratorAgentic Prompt GeneratorCompany ResearchCover Letter Generator
  • XpertoAI
  • MVP Ready
  • Resources

    CertificationsTopicsExpertsCollectionsArticlesQuestionsVideosJobs
logologo

Elevate Your Coding with our comprehensive articles and niche collections.

Useful Links

  • Contact Us
  • Privacy Policy
  • Terms & Conditions
  • Refund & Cancellation
  • About Us

Resources

  • Xperto-AI
  • Certifications
  • Python
  • GenAI
  • Machine Learning

Interviews

  • DSA
  • System Design
  • Design Patterns
  • Frontend System Design
  • ReactJS

Procodebase © 2024. All rights reserved.

Level Up Your Skills with Xperto-AI

A multi-AI agent platform that helps you level up your development skills and ace your interview preparation to secure your dream job.

Launch Xperto-AI

Building a Pagination Component in React

author
Generated by
Abhishek Goyan

14/09/2024

React

Sign in to read full article

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.

Step 1: Setting Up the Project

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.

Step 2: Create Sample Data

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.

Step 3: Creating the Pagination Component

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;

Explanation:

  1. 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.
  2. Calculating Total Pages: The total number of pages is computed by dividing the total items by items per page.

  3. Rendering Buttons: We create an array of buttons for each page number and render them.

Step 4: Implementing the Main Component

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;

Explanation:

  1. State Management: We use the useState hook to keep track of the currentPage.

  2. Data Slicing: The selected items for the current page are sliced from the original data based on the currentPage.

  3. Rendering: We display the list of items and include the Pagination component, passing in the appropriate props.

Step 5: Styling the Component

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; }

Explanation:

  • We added styles for the .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!

Popular Tags

ReactPaginationJavaScript

Share now!

Like & Bookmark!

Related Collections

  • Mastering React Concepts

    24/08/2024 | ReactJS

  • React Interview Challenges: Essential Coding Problems

    14/09/2024 | ReactJS

Related Articles

  • Mastering React JS Performance Optimization

    22/09/2024 | ReactJS

  • Parent Child Communication in React JS

    16/07/2024 | ReactJS

  • Components: The Building Blocks of React

    24/08/2024 | ReactJS

  • Lists and Keys: Rendering Multiple Items in React

    24/08/2024 | ReactJS

  • Performance Optimization in React: Techniques and Best Practices

    24/08/2024 | ReactJS

  • Implementing a Dynamic Theme Switcher (Light/Dark Mode) in Your Web Application

    14/09/2024 | ReactJS

  • Build a Context-Based State Management System in React

    14/09/2024 | ReactJS

Popular Category

  • Python
  • Generative AI
  • Machine Learning
  • ReactJS
  • System Design