[React] Pagination (Query String)

limes·1일 전
0
post-thumbnail

Javascript React Pagination

Pagination 기능

  • Cart.js
const [currentPage, setCurrentPage] = useState(1);
const PRODUCTSPERPAGE = 3;
const indexOfLastProduct = currentPage * PRODUCTSPERPAGE;
const indexOfFirstProduct = indexOfLastProduct - PRODUCTSPERPAGE;
const currentList = products.slice(indexOfFirstProduct, indexOfLastProduct);

const paginate = (pageNumber) => setCurrentPage(pageNumber);
  • 백엔드 API 통신 시 limit& offset 설정
useEffect(() => {
    const fetchData = async () => {
    const result = await axios.get(
        `http://${api}/cart?limit=${PRODUCTSPERPAGE}&offset=${
          (currentPage - 1) * 3 + 1
        }`,
        {
          headers: { Authorization: localStorage.getItem("token") },
        }
      );
      setCurrentPage(currentPage);
    };
    fetchData();
  }, [currentPage, productsPerPage]);
  • Pagination page
import React from "react";
import styled from "styled-components";

export default function Pagination({
  productsPerPage,
  paginate,
  currentPage,
  count,
}) {
  const pageArrLength = Math.ceil(count / productsPerPage);
  const pageNumber = Array(pageArrLength)
    .fill(1)
    .map((el, idx) => el + idx);

  
  return (
    <PageContainer currentPage={currentPage} className="pagination">
      {pageNumber.map((pageNum) => (
        <li
          key={pageNum}
          onClick={() => paginate(pageNum)}
        >
          {pageNum}
        </li>
      ))}
    </PageContainer>
  );
}

0개의 댓글