페이지네이션

728x90
반응형

const ProductsList = () => {
  const [currentPage, setCurrentPage] = useState(1);

  const {data: products, isLoading, isError} = useQuery('products', ProductsList);
 

  const handlePageChange = newPage => {
    setCurrentPage(newPage);
  };

  return (
    <>
        <BottomProducts page={currentPage} />
        <Pagination
          currentPage={currentPage}
          itemsPerPage={5}
          totalItems={products.length}
          onPageChange={handlePageChange}
        />
    </>
  );
};

 

 

 

const Pagination = ({currentPage, itemsPerPage, totalItems, onPageChange}) => {
  const totalPage = Math.ceil(totalItems / itemsPerPage);

  const handlePrevClick = () => {
    const prevPage = currentPage - 1;
    if (prevPage >= 1) {
      onPageChange(prevPage);
    }
  };

  const handleNextClick = () => {
    const nextPage = currentPage + 1;
    if (nextPage <= totalPage) onPageChange(nextPage);
  };

  return (
    <PageWrapper>
      <span>{`${currentPage} / ${totalPage}`}</span>
      <ButtonWrapper>
        <Button onClick={handlePrevClick} text="<" disabled={currentPage === 1}></Button>
        <Button onClick={handleNextClick} text=">" disabled={currentPage === totalPage}></Button>
      </ButtonWrapper>
    </PageWrapper>
  );
};


export default Pagination;

 

반응형