Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.1 kB
1
Indexable
Never
import React, { useState } from "react";

function Pagination({ itemsPerPage, data }) {
  const [currentPage, setCurrentPage] = useState(1);

  const totalPages = Math.ceil(data.length / itemsPerPage);

  const handleClick = (type) => {
    if (type === "prev") {
      setCurrentPage((prev) => prev - 1);
    } else if (type === "next") {
      setCurrentPage((prev) => prev + 1);
    }
  };

  const start = (currentPage - 1) * itemsPerPage;
  const end = start + itemsPerPage;
  const currentData = data.slice(start, end);

  return (
    <div>
      <ul>
        {currentData.map((item, index) => (
          <li key={index}>{item}</li>
        ))}
      </ul>
      <div>
        <button
          onClick={() => handleClick("prev")}
          disabled={currentPage === 1}
        >
          Previous
        </button>
        <span>{currentPage}</span>
        <button
          onClick={() => handleClick("next")}
          disabled={currentPage === totalPages}
        >
          Next
        </button>
      </div>
    </div>
  );
}

export default Pagination;