Simple Pagination in ReactJS: A Step-by-Step Guide

Simple Pagination in ReactJS: A Step-by-Step Guide
10 min read

Pagination is a fundamental feature in web applications that allows users to navigate through large sets of data in a more manageable and user-friendly way. In ReactJS applications, implementing simple pagination is a common requirement when dealing with extensive lists or tables of information.

In this comprehensive blog post, we will walk you through the process of implementing simple pagination in ReactJS. We will explore various pagination techniques, from basic manual pagination to more advanced automatic pagination with React hooks. By the end of this guide, you will have a solid understanding of how to integrate simple pagination in React JS projects, providing an enhanced user experience when dealing with large datasets.

What is Pagination?

Pagination is a technique used in web applications to divide large sets of data into smaller, more manageable chunks or pages. Instead of presenting all the data on a single page, pagination allows users to navigate through the data one page at a time, typically using navigation controls like "Previous" and "Next" buttons or page numbers.

In ReactJS applications, pagination is especially useful when dealing with lists, tables, or any other data that can grow large. By implementing pagination, developers can enhance user experience, reduce loading times, and improve overall performance.

The Importance of Pagination in ReactJS

Pagination plays a crucial role in ReactJS applications by:

  • Improving User Experience: Navigating through large datasets becomes more intuitive and user-friendly with pagination. Users can easily find the information they need without overwhelming amounts of data on a single page.

  • Reducing Data Loading Time: Pagination enables React applications to load and render only the necessary data for the current page, leading to faster loading times and improved performance.

  • Enhancing Performance: Smaller data sets result in optimized rendering and reduced memory usage, leading to a smoother user experience.

Setting Up the React Project

2.1 Create a New React App

To get started with implementing simple pagination in ReactJS application, let's create a new React app using the create-react-app tool. If you already have a React app set up, you can skip this step.

Open your terminal or command prompt and run the following command:

npx create-react-app simple-pagination-app

This will create a new React app named simple-pagination-app in a folder of the same name.

2.2 Install Required Dependencies

Next, navigate into the newly created app directory and install the required dependencies for our pagination implementation. We will need axios for making API requests (optional if you plan to fetch data from an external source) and classnames for dynamically applying CSS classes to our pagination controls.

cd simple-pagination-app
npm install axios classnames

With the dependencies installed, we are ready to start implementing simple pagination in our React app.

Manual Pagination in ReactJS

3.1 Implementing Manual Reactjs Pagination Logic

Manual pagination involves managing the current page number and the number of items displayed per page manually. We will create a functional component named ManualPagination that will handle the logic for manual pagination.

Let's define the basic structure of the component:

import React, { useState } from 'react';

const ManualPagination = ({ data, itemsPerPage }) => {
  const [currentPage, setCurrentPage] = useState(1);

  // Logic for slicing the data to display itemsPerPage on the current page
  const indexOfLastItem = currentPage * itemsPerPage;
  const indexOfFirstItem = indexOfLastItem - itemsPerPage;
  const currentItems = data.slice(indexOfFirstItem, indexOfLastItem);

  return (
    <div>
      {/* Display the items for the current page */}
      {currentItems.map((item) => (
        // Render individual items here
      ))}

      {/* Pagination controls go here */}
    </div>
  );
};

export default ManualPagination;

In the ManualPagination component, we initialize the currentPage state to 1, as the first page will be displayed initially. The itemsPerPage prop defines how many items should be displayed on each page.

To show the items for the current page, we use Array.prototype.slice() to extract the items corresponding to the current page number from the data array.

3.2 Creating Pagination Controls

Now that we have displayed the items for the current page, let's add the pagination controls to navigate between pages. For simplicity, we will use "Previous" and "Next" buttons to move between pages.

Update the ManualPagination component as follows:

import React, { useState } from 'react';

const ManualPagination = ({ data, itemsPerPage }) => {
  const [currentPage, setCurrentPage] = useState(1);

  // Logic for slicing the data to display itemsPerPage on the current page
  const indexOfLastItem = currentPage * itemsPerPage;
  const indexOfFirstItem = indexOfLastItem - itemsPerPage;
  const currentItems = data.slice(indexOfFirstItem, indexOfLastItem);

  // Function to handle the "Next" button click
  const handleNextPage = () => {
    setCurrentPage((prevPage) => prevPage + 1);
  };

  // Function to handle the "Previous" button click
  const handlePrevPage = () => {
    setCurrentPage((prevPage) => prevPage - 1);
  };

  return (
    <div>
      {/* Display the items for the current page */}
      {currentItems.map((item) => (
        // Render individual items here
      ))}

      {/* Pagination controls */}
      <div>
        <button onClick={handlePrevPage} disabled={currentPage === 1}>
          Previous
        </button>
        <button onClick={handleNextPage} disabled={indexOfLastItem >= data.length}>
          Next
        </button>
      </div>
    </div>
  );
};

export default ManualPagination;

In the updated ManualPagination component, we added two functions handleNextPage and handlePrevPage, which are triggered when the "Next" and "Previous" buttons are clicked, respectively. These functions update the currentPage state accordingly, and the indexOfLastItem and indexOfFirstItem variables are recalculated to display the correct set of items for the new page.

The "Previous" button is disabled when the current page is the first page (i.e., currentPage === 1), and the "Next" button is disabled when the last item of the current page is equal to or greater than the total number of items in the data array (i.e., indexOfLastItem >= data.length).

3.3 Displaying Paginated Data

With the manual pagination logic and pagination controls in place, we can now render the ManualPagination component and display the paginated data.

Assuming you have fetched the data from an API or have data available in the React parent component, you can pass the data and the number of items to display per page (itemsPerPage) as props to the ManualPagination component.

For example, in your parent component, you might have fetched data and stored it in a data state:

import React, { useState, useEffect } from 'react';
import axios from 'axios';
import ManualPagination from './ManualPagination';

const ParentComponent = () => {
  const [data, setData] = useState([]);

  useEffect(() => {
    // Fetch data from the API (replace 'apiEndpoint' with your actual API endpoint)
    axios.get('apiEndpoint')
      .then((response) => setData(response.data))
      .catch((error) => console.error('Error fetching data:', error));
  }, []);

  return (
    <div>
      {/* Pass the data and itemsPerPage as props to ManualPagination */}
      <ManualPagination data={data} itemsPerPage={10} />
    </div>
  );
};

export default ParentComponent;

In this example, we use the useState and useEffect hooks to fetch the data from an API endpoint and store it in the data state. We then pass the data and itemsPerPage as props to the ManualPagination component, setting the number of items to display per page to 10.

The ManualPagination component will take care of displaying the paginated data and handling pagination controls.

Conclusion

In this comprehensive blog post, we have explored the implementation of simple pagination in ReactJS applications using both manual and automatic pagination techniques. Pagination is a crucial feature when dealing with large datasets, and ReactJS provides various tools and hooks to make the implementation process efficient and user-friendly.

In conclusion, simple pagination in ReactJS is a powerful tool for creating user-friendly and efficient web applications. By choosing the appropriate pagination approach based on your specific use case and following best practices, you can enhance the overall user experience and make your React app more accessible and user-friendly.

If you are looking for expert guidance and support in ReactJS development, CronJ is the perfect partner for your project. CronJ is a leading technology company known for its expertise in software development, including React applications. Their team of highly skilled hire react.js developer possesses extensive knowledge of React best practices, modern trends, and cutting-edge technologies.

References

  1. https://twitter.com/reactjs
  2. error handling in react
  3. react split
  4. stateless components
In case you have found a mistake in the text, please send a message to the author by selecting the mistake and pressing Ctrl-Enter.
Jeff Smith 1K
Hello! My name is Jeff Smith. I’m a web designer and front-end web developer with over twenty years of professional experience in the design industry.
Comments (0)

    No comments yet

You must be logged in to comment.

Sign In / Sign Up