September 25, 2024

Md. Saad

Next.js is a popular open-source web development framework built on top of React and designed for building server-rendered React applications. Vercel developed it and has become widely adopted for its ability to streamline the development of highly performant, production-grade web applications. This article will discuss creating the Next js app, fetching data, and finally implementing a simple pagination in the project.
Before setting up the GitHub Actions workflow, the first and foremost step is to create a Next.js App. Use the following command to create a next.js app.
npx create-next-app@latest app-name
As it is not an article on creating the next.js app, we will not discuss it in detail. If you want to read it in detail follow the link.
After Creating a Next js app, Let’s create components. We will create two components. One is for posts and another is for pagination. Let’s create a Posts component first.
"use client";
import React from "react";
import {useState} from "react";
import Pagination from "./Pagination";
export default function Posts({postData}) {
const [currentPage, setCurrentPage] = useState(1);
const itemsPerPage = 9;
const totalPage = Math.ceil(postData.length / itemsPerPage);
const paginateData = () => {
const startIndex = (currentPage - 1) * itemsPerPage;
const endIndex = startIndex + itemsPerPage;
return postData.slice(startIndex, endIndex);
};
const currentPageData = paginateData();
const goToNextPage = () => {
setCurrentPage((prevPage) => prevPage + 1);
};
const goToPreviousPage = () => {
setCurrentPage((prevPage) => prevPage - 1);
};
const paginateFunction = {
totalPage,
currentPage,
setCurrentPage,
goToNextPage,
goToPreviousPage,
};
return (
<>
<h1 className="text-4xl font-bold"> List of Sample Blog </h1>
<ul className="grid grid-cols-3 gap-5">
{currentPageData.map((post) => (
<li
key={post.id}
className="mb-5 bg-gray-600 p-10"
>
<h2 className="text-cyan-600 font-semibold mb-2 text-xl ">{post.title}</h2>
<p>{post.content}</p>
</li>
))}
</ul>
<Pagination paginateFunction={paginateFunction} />
</>
);
}In this example, The Posts component accepts a prop postData, which contains an array of blog posts. It uses pagination to display a specific number of posts per page, along with navigation to move between pages. Let’s analyze the codes:
So far, we have discussed the variable. Let’s discuss what the code is rendering:
const Pagination = ({paginateFunction}) => {
const {totalPage, currentPage, setCurrentPage, goToNextPage, goToPreviousPage} = paginateFunction;
return (
<div className="container">
<ul className="flex items-center justify-center gap-2">
<li className="group">
<button
onClick={() => {
goToPreviousPage();
}}
className={`group flex items-center justify-center rounded-full border border-borderColor text-sm font-medium duration-300 dark:border-borderColor-dark p-2.5 ${
currentPage === 1 ? "disabled:opacity-7 cursor-not-allowed" : "cursor-pointer hover:bg-primary"
}`}
disabled={currentPage === 1}
>
Previous
</button>
</li>
{Array.from({length: totalPage}, (_, index) => (
<li
className={`group ${index + 1 === currentPage && "page-active"}`}
key={index}
>
<button
href=""
className="flex h-10 w-10 items-center justify-center rounded-full text-sm font-medium duration-300 hover:bg-cyan-600 hover:text-white group-[.page-active]:bg-cyan-600 dark:group-[.page-active]:text-white"
onClick={() => setCurrentPage(index + 1)}
>
{index + 1}
</button>
</li>
))}
<li className="group">
<button
onClick={() => {
goToNextPage();
}}
className={`group flex items-center justify-center rounded-full border border-borderColor text-sm font-medium duration-300 dark:border-borderColor-dark p-2.5 ${
currentPage === totalPage ? "disabled:opacity-7 cursor-not-allowed" : "cursor-pointer hover:bg-primary"
}`}
disabled={currentPage === totalPage}
>
Next
</button>
</li>
</ul>
</div>
);
};
export default Pagination;In this example, these codes are designed to display pagination controls (e.g., page numbers, "Previous" and "Next" buttons) for navigating through multiple pages of content. Here's a breakdown of how the component works:
Thus the Pagination component is ready to use for pagination. Finally, we need to fetch the data and show them.
Now it is time to fetch data and show them on our site.
import Posts from "@/components/Posts";
export default async function Home() {
let data = await fetch("https://api.vercel.app/blog");
let posts = await data.json();
return (
<div className="container mx-auto grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20 font-[family-name:var(--font-geist-sans)]">
<main className="flex flex-col gap-8 row-start-2 items-center sm:items-start">
<Posts postData={posts} />
</main>
</div>
);
}In this Example:
All of that is there for us to view on the webpage. Run npm run dev, and execute the code. Each page can be accessed by using pagination.
Adding pagination to your Next.js app enhances the user experience by efficiently handling large data sets, whether fetched from an API or a database. You can implement pagination on a Next js app. Thus, we can ensure seamless navigation between data pages, improving the overall usability of your application.
I hope that this article provides you with some valuable information. Please do not hesitate to contact StaticMania with any questions or feedback. Happy coding!