nick
nick

Reputation: 19

How to change pagination numbers using Reactjs

I am working on Reactjs (nextjs) and i am integrating "Nextjs" framework,I integrated pagination successfully but creating buttons like "1,2,3,20" but i want button should display "1,2...20" (Right now displaying all numbers,should use "..." after 2 buttons),how can i do this ? Here is my code in Allblogs.js

import Pagination from '../Pagination';
import { paginate } from "../../utils/paginate";
function Allblogs() {
  const pageSize = 1;
  const [posts,setPosts]=useState([]);
  const [currentPage, setCurrentPage] = useState(1);  
  
  useEffect(() => {
    const getPosts = async () => {
      const { data: res } = await axios.get(
        "xxxxxxxxxxxxxxxxxxxxxxxx"
      );
      setPosts(res);
      
    };
    getPosts();
  }, []);
  
  const handlePageChange = (page) => {
    setCurrentPage(page);
  };

  const paginatePosts = paginate(posts, currentPage, pageSize);
  const router = useRouter();
  useEffect(() => {
  }, [router.query]);
}
return (
    <>
      {paginatePosts.map((post, index) => {
              // displaing blogs data
  })} 
 <Pagination items={posts.length} pageSize={pageSize} currentPage={currentPage} onPageChange={handlePageChange} />
 </>

Here is my code in "Pagination.js"

import _ from "lodash";
const Pagination = ({ items, pageSize, currentPage, onPageChange }) => {
  const pageCount = items / pageSize;
  if (Math.ceil(pageCount) === 1) return null;
  const pages = _.range(1, pageCount + 1);
  return (
    <>
      <nav>
        <ul className="pagination">
          {pages.map((page) => (
            <li
              key={page}
              className={
                page === currentPage ? "page-item active" : "page-item"
              }
            >
              <a
                style={{ cursor: "pointer" }}
                onClick={() => onPageChange(page)}
                className="page-link"
              >
                {page}
              </a>
            </li>
          ))}
        </ul>
      </nav>
    </>
  );
};

export default Pagination;

Upvotes: 0

Views: 1589

Answers (2)

RubenSmn
RubenSmn

Reputation: 4662

If you don't want to use a library. I was trying to solve this using a custom hook.

import { useState } from "react";

const usePagination = (pageCount) => {
  const [current, setCurrent] = useState(1);
  const previous = current - 1;
  const next = current + 1;
  const last = pageCount;
  const first = 1;

  const hasBetweenPreviousAndFirst =
    next - current > 0 && current !== first && previous - first > 1;
  const hasBetweenNextAndLast =
    next - current > 0 && current !== last && last - next > 1;

  const onPageChange = (newPage) => {
    setCurrent(newPage);
  };

  return {
    previous,
    current,
    next,
    first,
    last,
    onPageChange,
    hasBetweenPreviousAndFirst,
    hasBetweenNextAndLast,
  };
};

Which I used like this in your Pagination component. I removed the state from the Allblogs component since the state is now handled by the custom hook. But you could pass it down and use it in the hook.

const Pagination = ({
  items,
  pageSize,
}: {
  items;
  pageSize;
}) => {
  const pageCount = items / pageSize;
  if (Math.ceil(pageCount) === 1) return null;

  const {
    previous,
    current,
    next,
    first,
    last,
    onPageChange,
    hasBetweenPreviousAndFirst,
    hasBetweenNextAndLast,
  } = usePagination(items);

  return (
    <nav>
      <ul className="pagination">
        {current !== first && (
          <li className="page-item">
            <a
              style={{ cursor: "pointer" }}
              onClick={() => onPageChange(first)}
              className="page-link"
            >
              {first}
            </a>
          </li>
        )}
        {hasBetweenPreviousAndFirst && <li>...</li>}
        {previous > first && (
          <li className="page-item">
            <a
              style={{ cursor: "pointer" }}
              onClick={() => onPageChange(previous)}
              className="page-link"
            >
              {previous}
            </a>
          </li>
        )}
        <li className="page-item active">{current}</li>
        {next < last && (
          <li className="page-item">
            <a
              style={{ cursor: "pointer" }}
              onClick={() => onPageChange(next)}
              className="page-link"
            >
              {next}
            </a>
          </li>
        )}
        {hasBetweenNextAndLast && <li>...</li>}
        {current !== last && (
          <li className="page-item">
            <a
              style={{ cursor: "pointer" }}
              onClick={() => onPageChange(last)}
              className="page-link"
            >
              {last}
            </a>
          </li>
        )}
      </ul>
    </nav>
  );
};

export default Pagination;

Upvotes: 0

Sahil Verma
Sahil Verma

Reputation: 61

A very easy and effective way to handle the pagination in ReactJs/Nextjs, By using the react-paginate library.

 <ReactPaginate
    breakLabel="..."
    nextLabel="next >"
    onPageChange={handlePageClick}
    pageRangeDisplayed={2}
    pageCount={200}
    previousLabel="< previous"
    forcePage = {CurrentPage}
  />

to set current page use - forcePage = {PageNumber}
to set total Pages use - pageCount = {200}
to handle click use - onPageChange = {handlePageClick}

Upvotes: 1

Related Questions