Implementing Pagination in Javascript

To implement pagination in a React application, you’ll need to split your data into multiple pages, and add navigation links to allow the user to switch between them.

Here is an example of how you might do this in a functional React component:

 

import React, { useState } from 'react';

const itemsPerPage = 10; // number of items to display per page

function PaginatedList({ items }) {
  const [currentPage, setCurrentPage] = useState(1);

  // slice the items array to get the items for the current page
  const currentItems = items.slice(
    (currentPage - 1) * itemsPerPage,
    currentPage * itemsPerPage
  );

  // create the pagination links
  const pageNumbers = [];
  for (let i = 1; i <= Math.ceil(items.length / itemsPerPage); i++) {
    pageNumbers.push(i);
  }
  const paginationLinks = pageNumbers.map((number) => (
    <button key={number} onClick={() => setCurrentPage(number)}>
      {number}
    </button>
  ));

  return (
    <>
      {currentItems.map((item) => (
        <div key={item.id}>{item.name}</div>
      ))}
      <div>{paginationLinks}</div>
    </>
  );
}

This code will create a list of items, split them into pages, and add a set of buttons to navigate between the pages. You can customize the number of items displayed per page and the appearance of the pagination links by modifying the relevant variables and styles.

Leave a Reply

Your email address will not be published. Required fields are marked *