To create pagination in Next.js, you can follow these steps:
- Determine the number of items you want to display per page and the total number of items.
- Create a page component that will display the items for each page. This component will receive two props:
items
, an array of items to display, andpage
, the current page number. - In your main page component, import the
useRouter
hook from thenext/router
module to get access to the current URL. - Extract the current page number from the URL using the
query
property of theuseRouter
hook. - Calculate the number of pages based on the total number of items and the items per page.
- Render a list of page numbers, with each number linking to the corresponding page.
- Render the page component with the appropriate items based on the current page number.
Here’s an example implementation:
import { useRouter } from 'next/router';
const PAGE_SIZE = 10;
function Page({ items, page }) {
const startIndex = (page - 1) * PAGE_SIZE;
const endIndex = startIndex + PAGE_SIZE;
const displayedItems = items.slice(startIndex, endIndex);
return (
<div>
<ul>
{displayedItems.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
</div>
);
}
export default function MyPage({ items }) {
const router = useRouter();
const { query } = router;
const currentPage = query.page ? parseInt(query.page, 10) : 1;
const numPages = Math.ceil(items.length / PAGE_SIZE);
return (
<div>
<ul>
{Array.from({ length: numPages }, (_, i) => (
<li key={i}>
<Link href={`/?page=${i + 1}`}>
<a>{i + 1}</a>
</Link>
</li>
))}
</ul>
<Page items={items} page={currentPage} />
</div>
);
}
In this example, we assume that each item in the items
array has an id
and a name
property. We use the Link
component from Next.js to create links to each page. The startIndex
and endIndex
variables are used to calculate the slice of items to display on the current page.