Adding Pagination to a Next.js Application: A Step-by-Step Guide
Setting Up the Project
To get started, create a new Next.js project using the command npx create-next-app next-pagination
. Then, navigate into the project directory and run yarn dev
or npm run dev
to start the development server.
Data Fetching with getStaticProps
For this example, we’ll use the JSON Placeholder API to fetch data. We’ll use the getStaticProps
function to pre-render the page at build-time using the props returned by getStaticProps
. The Fetch API will be used to retrieve data from the API endpoint.
import fetch from 'isomorphic-unfetch';
const HomePage = ({ posts }) => {
return (
{posts.map((post) => (
// render post component
))}
);
};
export const getStaticProps = async () => {
const response = await fetch('undefinedjsonplaceholder.typicode.com/posts');
const posts = await response.json();
return {
props: {
posts,
},
};
};
Implementing the Pagination Component
Create a new file called Pagination.js
in the components directory. This component will receive four props: items
, currentPage
, pageSize
, and onPageChange
.
import React from 'react';
const Pagination = ({ items, currentPage, pageSize, onPageChange }) => {
const pagesCount = Math.ceil(items.length / pageSize);
const pages = Array.from({ length: pagesCount }, (_, index) => index + 1);
return (
{pages.map((page) => (
onPageChange(page)}
className={currentPage === page ? ‘active’ : ”}
>
{page}
))}
);
};
export default Pagination;
Adding the Pagination Helper Function
Create a new file called paginate.js
in the utils directory. This function will take three arguments: items
, pageNumber
, and pageSize
.
const paginate = (items, pageNumber, pageSize) => {
const startIndex = (pageNumber - 1) * pageSize;
return items.slice(startIndex, startIndex + pageSize);
};
export default paginate;
Using the Pagination Component
Import the Pagination component in your HomePage component and pass the required props.
import Pagination from '../components/Pagination';
import paginate from '../utils/paginate';
import { useState } from 'react';
const HomePage = ({ posts }) => {
const [currentPage, setCurrentPage] = useState(1);
const [pageSize, setPageSize] = useState(10);
const paginatedPosts = paginate(posts, currentPage, pageSize);
const onPageChange = (page) => {
setCurrentPage(page);
};
return (
// render post component
))}
);
};