React js Pagination Practice Questions with Solutions

Introduction

Pagination is used to divide a large amount of data into smaller pages so users can view a limited number of items at a time. In React, pagination can be created using state, array methods, and simple calculations. It is commonly used in product lists, student records, dashboards, tables, and API-based applications. In this chapter, we will solve practical questions covering page numbers, next and previous buttons, items per page, and dynamic pagination. React js Pagination practice questions with solutions help to understand the concepts.

1. What is Pagination in React?

Pagination is a technique used to divide a large list of data into multiple smaller pages.

For example, if you have 100 products, displaying all 100 products at once may make the page difficult to use.

Instead, you can display:

Page 1 → Products 1–10
Page 2 → Products 11–20
Page 3 → Products 21–30

React can manage the current page using useState().


2. How do you create basic pagination in React?

You can use slice() to display only a specific part of an array.

Solution:

import { useState } from "react";

function App() {
  const [currentPage, setCurrentPage] = useState(1);

  const products = [
    "Laptop",
    "Mobile",
    "Keyboard",
    "Mouse",
    "Monitor",
    "Headphones",
    "Tablet",
    "Camera"
  ];

  const itemsPerPage = 3;

  const startIndex = (currentPage - 1) * itemsPerPage;
  const currentItems = products.slice(
    startIndex,
    startIndex + itemsPerPage
  );

  return (
    <div>
      <h2>Products</h2>

      {currentItems.map((product) => (
        <p key={product}>{product}</p>
      ))}

      <button onClick={() => setCurrentPage(1)}>
        Page 1
      </button>

      <button onClick={() => setCurrentPage(2)}>
        Page 2
      </button>

      <button onClick={() => setCurrentPage(3)}>
        Page 3
      </button>
    </div>
  );
}

export default App;

Here, slice() selects only the items that belong to the current page.


3. How do you calculate the starting index for pagination?

The starting index can be calculated using:

const startIndex = (currentPage - 1) * itemsPerPage;

For example, if:

currentPage = 2;
itemsPerPage = 10;

Then:

(2 - 1) × 10 = 10

So the second page starts from index 10.

This calculation is commonly used with slice().

const currentItems = products.slice(
  startIndex,
  startIndex + itemsPerPage
);


4. How do you create Next and Previous buttons?

You can update the current page using setCurrentPage().

Solution:

import { useState } from "react";

function App() {
  const [currentPage, setCurrentPage] = useState(1);

  const products = [
    "Laptop",
    "Mobile",
    "Keyboard",
    "Mouse",
    "Monitor",
    "Headphones"
  ];

  const itemsPerPage = 2;

  const startIndex =
    (currentPage - 1) * itemsPerPage;

  const currentItems = products.slice(
    startIndex,
    startIndex + itemsPerPage
  );

  const totalPages = Math.ceil(
    products.length / itemsPerPage
  );

  return (
    <div>
      {currentItems.map((product) => (
        <p key={product}>{product}</p>
      ))}

      <button
        disabled={currentPage === 1}
        onClick={() =>
          setCurrentPage((page) => page - 1)
        }
      >
        Previous
      </button>

      <span> Page {currentPage} of {totalPages} </span>

      <button
        disabled={currentPage === totalPages}
        onClick={() =>
          setCurrentPage((page) => page + 1)
        }
      >
        Next
      </button>
    </div>
  );
}

export default App;

The disabled property prevents the user from going beyond the first or last page.


5. How do you calculate the total number of pages?

Use Math.ceil().

const totalPages = Math.ceil(
  products.length / itemsPerPage
);

For example:

Total products = 25
Items per page = 10

25 / 10 = 2.5

Using Math.ceil():

Total pages = 3

The third page contains the remaining 5 products.


6. How do you create page number buttons dynamically?

Instead of manually creating every page button, you can generate them using Array.from().

Solution:

import { useState } from "react";

function App() {
  const [currentPage, setCurrentPage] = useState(1);

  const products = [
    "Laptop",
    "Mobile",
    "Keyboard",
    "Mouse",
    "Monitor",
    "Headphones",
    "Tablet",
    "Camera",
    "Speaker"
  ];

  const itemsPerPage = 3;

  const totalPages = Math.ceil(
    products.length / itemsPerPage
  );

  const startIndex =
    (currentPage - 1) * itemsPerPage;

  const currentItems = products.slice(
    startIndex,
    startIndex + itemsPerPage
  );

  return (
    <div>
      {currentItems.map((product) => (
        <p key={product}>{product}</p>
      ))}

      {Array.from(
        { length: totalPages },
        (_, index) => (
          <button
            key={index + 1}
            onClick={() => setCurrentPage(index + 1)}
          >
            {index + 1}
          </button>
        )
      )}
    </div>
  );
}

export default App;

If there are 3 pages, React generates:

1  2  3

Each button changes the current page.


7. How do you highlight the active pagination page?

You can compare the button’s page number with currentPage.

Solution:

{Array.from(
  { length: totalPages },
  (_, index) => {
    const pageNumber = index + 1;

    return (
      <button
        key={pageNumber}
        onClick={() => setCurrentPage(pageNumber)}
        style={{
          fontWeight:
            currentPage === pageNumber
              ? "bold"
              : "normal"
        }}
      >
        {pageNumber}
      </button>
    );
  }
)}

When the current page is 2, the button for page 2 receives the bold style.

You can use CSS classes instead for a more complete design.


8. How do you disable the Previous and Next buttons correctly?

The Previous button should be disabled on the first page, while the Next button should be disabled on the last page.

<button
  disabled={currentPage === 1}
  onClick={() =>
    setCurrentPage((page) => page - 1)
  }
>
  Previous
</button>

<button
  disabled={currentPage === totalPages}
  onClick={() =>
    setCurrentPage((page) => page + 1)
  }
>
  Next
</button>

This prevents invalid page numbers such as:

Page 0
Page 4

when the available pages are only 1–3.


9. How do you add an Items Per Page option?

You can allow users to choose how many items they want to see on each page.

Solution:

import { useState } from "react";

function App() {
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(3);

  const products = [
    "Laptop",
    "Mobile",
    "Keyboard",
    "Mouse",
    "Monitor",
    "Headphones",
    "Tablet",
    "Camera",
    "Speaker"
  ];

  const totalPages = Math.ceil(
    products.length / itemsPerPage
  );

  const startIndex =
    (currentPage - 1) * itemsPerPage;

  const currentItems = products.slice(
    startIndex,
    startIndex + itemsPerPage
  );

  const handleItemsPerPageChange = (event) => {
    setItemsPerPage(Number(event.target.value));
    setCurrentPage(1);
  };

  return (
    <div>
      <select
        value={itemsPerPage}
        onChange={handleItemsPerPageChange}
      >
        <option value="3">3 Items</option>
        <option value="5">5 Items</option>
        <option value="10">10 Items</option>
      </select>

      {currentItems.map((product) => (
        <p key={product}>{product}</p>
      ))}

      <button
        disabled={currentPage === 1}
        onClick={() =>
          setCurrentPage((page) => page - 1)
        }
      >
        Previous
      </button>

      <span>
        {" "}Page {currentPage} of {totalPages}{" "}
      </span>

      <button
        disabled={currentPage === totalPages}
        onClick={() =>
          setCurrentPage((page) => page + 1)
        }
      >
        Next
      </button>
    </div>
  );
}

export default App;

When the number of items per page changes, resetting the page to 1 helps avoid ending up on a page that no longer exists.


10. How do you build a practical Product Pagination application?

You can combine page numbers, Next/Previous buttons, product objects, and dynamic rendering.

Solution:

import { useState } from "react";

function ProductPagination() {
  const [currentPage, setCurrentPage] = useState(1);

  const products = [
    { id: 1, name: "Laptop", price: 60000 },
    { id: 2, name: "Mobile", price: 30000 },
    { id: 3, name: "Keyboard", price: 1500 },
    { id: 4, name: "Mouse", price: 800 },
    { id: 5, name: "Monitor", price: 12000 },
    { id: 6, name: "Headphones", price: 5000 },
    { id: 7, name: "Tablet", price: 25000 },
    { id: 8, name: "Camera", price: 40000 },
    { id: 9, name: "Speaker", price: 3000 },
    { id: 10, name: "Printer", price: 10000 }
  ];

  const itemsPerPage = 3;

  const totalPages = Math.ceil(
    products.length / itemsPerPage
  );

  const startIndex =
    (currentPage - 1) * itemsPerPage;

  const currentProducts = products.slice(
    startIndex,
    startIndex + itemsPerPage
  );

  return (
    <div>
      <h2>Product List</h2>

      {currentProducts.map((product) => (
        <div key={product.id}>
          <h3>{product.name}</h3>
          <p>Price: ₹{product.price}</p>
        </div>
      ))}

      <div>
        <button
          disabled={currentPage === 1}
          onClick={() =>
            setCurrentPage((page) => page - 1)
          }
        >
          Previous
        </button>

        {Array.from(
          { length: totalPages },
          (_, index) => {
            const pageNumber = index + 1;

            return (
              <button
                key={pageNumber}
                onClick={() =>
                  setCurrentPage(pageNumber)
                }
                style={{
                  fontWeight:
                    currentPage === pageNumber
                      ? "bold"
                      : "normal"
                }}
              >
                {pageNumber}
              </button>
            );
          }
        )}

        <button
          disabled={currentPage === totalPages}
          onClick={() =>
            setCurrentPage((page) => page + 1)
          }
        >
          Next
        </button>
      </div>

      <p>
        Page {currentPage} of {totalPages}
      </p>
    </div>
  );
}

export default ProductPagination;

This example demonstrates the basic client-side pagination pattern:

Full Data
   ↓
Calculate Total Pages
   ↓
Calculate Start Index
   ↓
Use slice()
   ↓
Display Current Page
   ↓
Change Page

For large datasets loaded from an API, pagination can instead be handled by the server by requesting only the required page of data.

Key Takeaways

  • Pagination divides a large dataset into smaller pages.
  • useState() can store the current page.
  • slice() can select the items for the current page.
  • The starting index is commonly calculated with (currentPage - 1) * itemsPerPage.
  • Math.ceil() can calculate the total number of pages.
  • Previous and Next buttons can update the current page.
  • Disable Previous on the first page.
  • Disable Next on the last page.
  • Array.from() can be used to generate page buttons dynamically.
  • Changing the items-per-page value may require resetting the current page.
  • Client-side pagination works well for data already available in the browser.
  • Large datasets often benefit from server-side pagination.

FAQs

1. What is pagination in React?

Pagination is a technique for dividing a large amount of data into smaller pages and displaying only a limited number of items at a time.

2. Which JavaScript method is commonly used for React pagination?

The slice() method is commonly used when implementing client-side pagination because it can select a portion of an array without changing the original array.

3. How do you calculate total pages in React?

You can use:

const totalPages = Math.ceil(
  items.length / itemsPerPage
);

4. How do you create a Next button in React pagination?

You can update the current page using a functional state updater:

setCurrentPage((page) => page + 1);

The button should also be disabled when the current page is the last page.

5. How do you create a Previous button?

Use:

setCurrentPage((page) => page - 1);

The Previous button should be disabled when:

currentPage === 1

6. What is the difference between client-side and server-side pagination?

In client-side pagination, the application already has the dataset and selects which items to display in the browser.

In server-side pagination, the application requests only the required page of data from the server or API.

Server-side pagination is generally more suitable when the dataset is very large.

7. Can pagination be combined with search, filtering, and sorting?

Yes. A common approach is to apply search and filtering first, sort the resulting data when needed, and then paginate the final result.

For example:

const result = products
  .filter((product) => product.category === "Electronics")
  .sort((a, b) => a.price - b.price);

const currentProducts = result.slice(
  startIndex,
  startIndex + itemsPerPage
);

The exact order can depend on the application’s requirements.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top