website-logomedCode

Implementing Pagination in a Next.js 15 Server-Side Component

Pagination is a crucial aspect of building scalable web applications, especially for content-heavy websites like blogs, product listings, or dashboards. In this guide, we’ll walk you through the process of implementing pagination in Next.js 15
mohammed dakir| November 4, 2024
next.js
Implementing Pagination in a Next.js 15 Server-Side Component

#Pagination #server-side #next.js15 #tools

Why Server-Side Pagination?

Server-side pagination is particularly beneficial for applications with vast amounts of data that cannot be fully loaded on the client side. By fetching only the required data based on page requests, we reduce load times and optimize resource usage. Next.js 15, with its updated server-side capabilities, allows us to implement robust and SEO-friendly pagination effortlessly.

Step 1: Creating the Data Source for Pagination

We need a source of data to paginate through. This could be a database like MongoDB or a REST API. For simplicity, let’s assume we’re fetching paginated data from a MongoDB collection.

Creat action.js and write this function. /Article.js is Modul of MongoDb and connect.js is function to connect database

"use server";
importArticlefrom"./Acticle";
importconnectfrom"../component/mongo";

exportconstgetPosts=async (page) => {
  try {
    connect();
    constpageSize=3; // that number page showing first page
    constpageNumber=page||1// that searchParams or page number
    constcount=awaitArticle.find({}).countDocuments();
    constposts=awaitArticle.find({}).limit(pageSize).skip((pageNumber)*pageSize);
    consttotalPage=Math.ceil(count/pageSize) // that total of page blogs
    return {posts,totalPage};
  } catch (err) {
    console.log(err);
    thrownewError("Failed to fetch posts!");
  }
};

Step 2: Building BlogSection component

past this code in page.js

import BlogSection from "./component/BlogSection";
import { getPosts } from "./lib/action";

export default async function Home({ searchParams }) {
  const { page } = await searchParams;
  const currentPage = parseInt(page);
  const data = await getPosts(page);
  console.log(data);
  return (
     <div className="">
      <BlogSection
        data={data.posts}
        totalPages={data.totalPage}
        currentPage={currentPage}
      />
    </div>
  );
}

Create BlogSection.jsx

import React from "react";
import Card from "./Card";
import ServerPagination from "./Pagination";

const BlogSection = async ({ data, currentPage, totalPages }) => {
  return (
    <div className="bg-gray-100 md:px-10 px-4 font-[sans-serif]">
      <div className="max-w-5xl max-lg:max-w-3xl max-sm:max-w-sm mx-auto">
        <div className="flex justify-around items-center mb-8">
          <h2 className="text-3xl font-extrabold text-gray-800 mt-4">
            Latest Blog Posts
          </h2>
        </div>
        <div className="flex flex-wrap">
          {data.map((post) => {
            return <Card key={post.id} post={post} />;
          })}
        </div>
        <ServerPagination totalPages={totalPages} currentPage={currentPage} />
      </div>
    </div>
  );
};

export default BlogSection;

Create Card.jsx component

import React from "react";
import Link from "next/link";
import Image from "next/image";

const Card = ({ post }) => {
  return (
    <div className="bg-white flex-grow-1 basis-52 rounded overflow-hidden w-96 ml-8 border border-yellow-600">
      <Image
        src={post.image}
        alt="Blog Post 1"
        className="w-full h-44 object-cover"
        width={400}
        height={300}
        loading="lazy"
        quality={80}
      />
      <div className="p-6">
        <h3 className="text-lg font-bold text-gray-800 mb-3">{post.title}</h3>
        <Link
          href={`/blogs/${post.id}`}
          className="mt-4 inline-block px-4 py-2 rounded tracking-wider bg-orange-500 hover:bg-orange-600 text-white text-[13px]"
        >
          Read More
        </Link>
      </div>
    </div>
  );
};

export default Card;


Step 2: Building the Pagination Logic in the Server-Side Component

import Link from "next/link";
import React from "react";

const ServerPagination = ({ totalPages, currentPage }) => {
  return (
    <div
      aria-label="Page navigation"
      className="flex justify-center flex-wrap mt-16 mb-10"
    >
      <Link
        href={`/?page=${currentPage - 1}`}
        className={`${
          currentPage === 1
            ? "hidden"
            : "flex items-center justify-center dark:bg-dark dark:text-light px-3 h-8 leading-tight text-gray-500 bg-white border border-gray-300 rounded-r-lg hover:bg-gray-100 hover:text-gray-700"
        }`}
      >
        Previous
      </Link>
      {Array.from({ length: totalPages }, (_, index) => (
        <div key={index}>
          <Link
            href={`/?page=${index + 1}`}
            className={`flex items-center justify-center px-3 h-8 leading-tight border ${
              currentPage === index + 1
                ? "bg-blue-500 text-white"
                : "bg-white text-gray-500 border-gray-300 dark:bg-dark dark:text-light hover:bg-gray-100 hover:text-gray-700"
            }`}
          >
            {index + 1}
          </Link>
        </div>
      ))}
      <Link
        href={`/?page=${currentPage + 1}`}
        className={`${
          totalPages === currentPage
            ? "hidden"
            : "flex items-center justify-center dark:bg-dark dark:text-light px-3 h-8 leading-tight text-gray-500 bg-white border border-gray-300 rounded-r-lg hover:bg-gray-100 hover:text-gray-700"
        }
        `}
      >
        Next
      </Link>
    </div>
  );
};

export default ServerPagination;

Conclusion

By following these steps, you’ve set up a powerful and SEO-friendly pagination system in Next.js 15, optimized for server-side rendering. Pagination ensures that your application remains efficient and user-friendly while handling large datasets. The server-side approach used here provides pre-rendered, SEO-optimized content, boosting your site's visibility on search engines.

Share

Explore the latest insights, articles,free components, and expert advice on programming and software development

© Copyright 2024 MED DAKIR. All rights reserved./privacy policyTerms & Conditions