Pagination in Next.js

In my last article, I wrote about the Next.js Page basic feature of data fetching, check it out here. With an understanding of these features, one can easily implement pagination in the app.

What is pagination?

Pagination is a method of breaking up a large amount of content into smaller sections or pages, which makes it easier for users to access and navigate. It improves the user experience by making it faster and simpler to find specific information, reduces page load times, and can improve a website's search engine optimization (SEO).

Implementing pagination in Next.js

The task of pagination is done by the database and also the total count is also known by the database, I will be this endpoint for the implementation.

https://api.punkapi.com/v2/beers?page=1&per_page=10

We will be treating the index page as page one, so in the pages/index.tsx file add the following code.

import Card from '@/components/Card'

export default function Home({ data }: any) {
return <div className='flex flex-wrap justify-center p-12'>
          {data.map((d: any, index: any) =>
            <Card key={index} data={d} />
          )}
    </div>
}
export const getStaticProps: GetStaticProps = async (GetStaticPropsContext) => {
  const response = await fetch(`https://api.punkapi.com/v2/beers?page=1&per_page=10`)
  const data = await response.json()

  return {
    props: {
      data: data,
    }
  }
}

and create a component/Card.tsx file and add the following code

const Card = ({ data }: any) => {
    return <div className="max-w-sm rounded overflow-hidden shadow-lg">
        <div className="px-6 py-4">
            <div className="font-bold text-xl mb-2">{data.name}</div>
            <p className="text-gray-700 text-base">
                Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatibus quia, nulla! Maiores et perferendis eaque, exercitationem praesentium nihil.
            </p>
        </div>
    </div>
}

export default Card

So after hitting the npm run dev command this should be rendered. So now for adding different pages add pages/[id].tsx file with the following code

import Card from "@/components/Card"

const PaginatedPage = ({ data, currentPage, perPage }: any) => {
    return <div>
        <div className='flex flex-wrap justify-center p-12'>
            {data?.map((d: any, index: any) =>
                <Card key={index} d={d} />
            )}
        </div>
    </div>
}

export const getStaticProps: GetStaticProps = async ({ params }: GetStaticPropsContext) => {
    const response = await fetch(`https://api.punkapi.com/v2/beers?page=${params?.id}&per_page=10`)
    const data = await response.json()
    const page = (params?.id) as string
    return {
        props: {
            data: data,
        }
    }
}

export const getStaticPaths: GetStaticPaths = async () => {
    return {
        // Prerender the next 2 pages after the first page
        paths: Array.from({ length: 2 }).map((_, i) => `/${i + 2}`),
        fallback: 'blocking', // can also be true or false
    }
}

so after this we have something like this

After building the app we can see that it will pre-render the first three pages that are index, /id - 2 and 3

For navigating between different pages we can add the pagination component

For this, one can refer to this repo. After integrating with it the final result will look like this.

So, using pagination in Next.js can improve performance, provide a better user experience, and increase flexibility in managing large sets of data by dividing them into smaller chunks.