Icon
Get In Touch
#nextjs

Basic "Load More" Pagination

Implement a basic pagination system with a "Load More" button in your Next.js application, ensuring that only a subset of items is displayed initially and more items are loaded incrementally.

Define Your Data

define the data array (initialItems) that you want to paginate.

1
const initialItems = [
2
{
3
href: "/nextjs/path-01",
4
title: "Title 01",
5
description: "Your description here.",
6
},
7
{
8
href: "/nextjs/path-02",
9
title: "Title 02",
10
description: "Your description here.",
11
},
12
// Add more items as needed
13
];

Add State Management

Add state management for the visible items and the current page number using useState. Add Loadmore functionality and conditional rendering of the button.

1
"use client"
2
import React, { useState } from "react";
3
import Link from "next/link";
4
5
// Define the number of items to display per "page"
6
const ITEMS_PER_PAGE = 4;
7
8
const MyComponent {
9
const [visibleItems, setVisibleItems] = useState(initialItems.slice(0, ITEMS_PER_PAGE));
10
const [currentPage, setCurrentPage] = useState(1);
11
12
// Function to load more items
13
const loadMoreItems = () => {
14
const newPage = currentPage + 1;
15
const newVisibleItems = initialItems.slice(0, newPage * ITEMS_PER_PAGE);
16
setVisibleItems(newVisibleItems);
17
setCurrentPage(newPage);
18
};
19
20
return (
21
<div>
22
<h1>Next.js Documentation</h1>
23
<div className="item-list">
24
{visibleItems.map((item, index) => (
25
<Link key={index} href={item.href}>
26
<a className="item">
27
<h2>{item.title}</h2>
28
<p>{item.description}</p>
29
</a>
30
</Link>
31
))}
32
</div>
33
// Conditional rendering of load more button
34
{visibleItems.length < initialItems.length && (
35
<button onClick={loadMoreItems}>Load More</button>
36
)}
37
</div>
38
);
39
};
40
41
export default MyComponent;

Pagination is a technique used to divide a large dataset into smaller chunks, or pages. This way, only a subset of the data is displayed at a time, which improves performance and user experience. In this example, we'll display 4 items initially and load 4 more each time the "Load More" button is clicked.

©2024 Codeblockz

Privacy Policy