#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.
1const initialItems = [2{3href: "/nextjs/path-01",4title: "Title 01",5description: "Your description here.",6},7{8href: "/nextjs/path-02",9title: "Title 02",10description: "Your description here.",11},12// Add more items as needed13];
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"2import React, { useState } from "react";3import Link from "next/link";45// Define the number of items to display per "page"6const ITEMS_PER_PAGE = 4;78const MyComponent {9const [visibleItems, setVisibleItems] = useState(initialItems.slice(0, ITEMS_PER_PAGE));10const [currentPage, setCurrentPage] = useState(1);1112// Function to load more items13const loadMoreItems = () => {14const newPage = currentPage + 1;15const newVisibleItems = initialItems.slice(0, newPage * ITEMS_PER_PAGE);16setVisibleItems(newVisibleItems);17setCurrentPage(newPage);18};1920return (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 button34{visibleItems.length < initialItems.length && (35<button onClick={loadMoreItems}>Load More</button>36)}37</div>38);39};4041export 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