Pagination is a common feature in web applications to manage large sets of data. In this article, we will build a pagination component in Next.js and provide an example of how to use it.

Prerequisites

Before we start, make sure you have the following installed:

  • Node.js
  • Next.js

Next.js Pagination Steps

Setting Up the Next.js Project

First, create a new Next.js project if you don’t already have one:

npx create-next-app next-pagination-example
cd next-pagination-example

Creating the Pagination Component

Create a new file called Pagination.js inside the components directory:

// components/Pagination.js
import React from 'react';

const Pagination = ({ currentPage, totalPages, onPageChange }) => {
  const handleClick = (page) => {
    if (page > 0 && page <= totalPages) {
      onPageChange(page);
    }
  };

  return (
    <div className="pagination">
      <button onClick={() => handleClick(currentPage - 1)} disabled={currentPage === 1}>
        Previous
      </button>
      {[...Array(totalPages)].map((_, index) => (
        <button
          key={index + 1}
          onClick={() => handleClick(index + 1)}
          className={currentPage === index + 1 ? 'active' : ''}
        >
          {index + 1}
        </button>
      ))}
      <button onClick={() => handleClick(currentPage + 1)} disabled={currentPage === totalPages}>
        Next
      </button>
      <style jsx>{`
        .pagination {
          display: flex;
          gap: 0.5rem;
          margin-top: 1rem;
        }
        .pagination button {
          padding: 0.5rem 1rem;
          border: none;
          background-color: #0070f3;
          color: white;
          cursor: pointer;
        }
        .pagination button:disabled {
          background-color: #eaeaea;
          cursor: not-allowed;
        }
        .pagination button.active {
          background-color: #005bb5;
        }
      `}</style>
    </div>
  );
};

export default Pagination;

Using the Pagination Component

Now, let’s use the Pagination component in a page. Create a new file called index.js inside the pages directory:

// pages/index.js
import React, { useState } from 'react';
import Pagination from '../components/Pagination';

const itemsPerPage = 10;
const totalItems = 100; // Example total items

const HomePage = () => {
  const [currentPage, setCurrentPage] = useState(1);

  const totalPages = Math.ceil(totalItems / itemsPerPage);

  const onPageChange = (page) => {
    setCurrentPage(page);
  };

  const currentItems = Array.from({ length: itemsPerPage }, (_, index) => ({
    id: index + 1 + (currentPage - 1) * itemsPerPage,
    name: `Item ${index + 1 + (currentPage - 1) * itemsPerPage}`,
  }));

  return (
    <div>
      <h1>Pagination Example</h1>
      <ul>
        {currentItems.map((item) => (
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>
      <Pagination currentPage={currentPage} totalPages={totalPages} onPageChange={onPageChange} />
    </div>
  );
};

export default HomePage;

Running the Application

Run the application using the following command:

npm run dev

Open your browser and navigate to http://localhost:3000. You should see a list of items with pagination controls.

Conclusion

In this article, we created a pagination component in Next.js and used it in a simple example. Pagination helps manage large datasets by breaking them into smaller, manageable pages. You can customize the component further to suit your needs.

For more updates on programming trends and tutorials, visit blogsea.net regularly.

Next.js Pagination – FAQs

What is pagination?

Pagination is a technique to divide a large dataset into smaller, manageable pages.

How do I create a pagination component in Next.js?

You can create a pagination component in Next.js using React state and event handlers to manage page changes.

How do I calculate the total number of pages?

Divide the total number of items by the number of items per page and round up to the nearest whole number.

How do I disable pagination buttons?

Disable pagination buttons when the current page is the first or last page using the disabled attribute.

Can I use the pagination component with dynamic data?

Yes, you can fetch data from an API and use the pagination component to navigate through the results.

Newsletter

I am a Software developer

My name is muhammad adnan and i am a professtional software developer. specialize in designing and developing efficient software applications.

Check out My Portfolio