본문 바로가기
Javascript&Typescript/React

[React] 리액트 pagination 적용

by clolee 2022. 9. 29.

react-js-pagination 사용

 

https://www.npmjs.com/package/react-js-pagination

 

npm i react-js-pagination

 

src/components/Paging.js

 

  • activePage : 현재 페이지
  • itemsCountPerPage : 한 페이지 당 보여줄 아이템 수
  •  totalItemsCount : 총 아이템 수
  • pageRangeDisplayed : paginator에서 보여줄 페이지 범위
  • prevPageText : 이전 페이지로 가기를 나타내는 텍스트
  • nextPageText : 다음 페이지로 가기를 나타내는 텍스트
  • onChange : 페이지가 바뀔 때 핸들링하는 함수
import React from "react";
import Pagination from "react-js-pagination";
import "./Paging.css";

const Paging = ({ page, count, setPage }) => {
  return (
    <div>
      <Pagination
        activePage={page}
        itemsCountPerPage={5}
        totalItemsCount={count}
        pageRangeDisplayed={5}
        prevPageText={"<"}
        nextPageText={">"}
        onChange={setPage}
      />
    </div>
  );
};

export default Paging;

 

src/components/Paging.css

.pagination {
    display: flex;
    justify-content: center;
    margin-top: 15px;
  }

  ul {
    list-style: none;
    padding: 0;
  }

  ul.pagination li {
    display: inline-block;
    width: 30px;
    height: 30px;
    border: 1px solid #e2e2e2;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 1rem;
  }

  ul.pagination li:first-child{
    border-radius: 5px 0 0 5px;
  }

  ul.pagination li:last-child{
    border-radius: 0 5px 5px 0;
  }

  ul.pagination li a {
    text-decoration: none;
    color: #337ab7;
    font-size: 1rem;
  }

  ul.pagination li.active a {
    color: white;
  }

  ul.pagination li.active {
    background-color: #337ab7;
  }

  ul.pagination li a:hover,
  ul.pagination li a.active {
    color: blue;
  }

  .page-selection {
    width: 48px;
    height: 30px;
    color: #337ab7;
  }

 

 

src/pages/ListProductsSalePage.js

 

  const [products, setProducts] = useState([]);  // 리스트에 나타낼 아이템들
  const [count, setCount] = useState(0); // 아이템 총 개수
  const [currentPage, setCurrentPage] = useState(1); // 현재 페이지. default 값으로 1
  const [postPerPage] = useState(5); // 한 페이지에 보여질 아이템 수 
  const [indexOfLastPost, setIndexOfLastPost] = useState(0); // 현재 페이지의 마지막 아이템 인덱스
  const [indexOfFirstPost, setIndexOfFirstPost] = useState(0); // 현재 페이지의 첫번째 아이템 인덱스
  const [currentPosts, setCurrentPosts] = useState(0); // 현재 페이지에서 보여지는 아이템들

count에는 아이템 리스트의 length를 set 해줌

import React, { useState, useEffect, createContext } from "react";
import ProgressBar from "../components/ProgressBar";
import {
  Box,
  Card,
  CardActions,
  CardContent,
  Divider,
  Button,
  Typography,
  Grid,
} from "@mui/material";
import axios from "axios";
import { useNavigate, Link } from "react-router-dom";
import Paging from "../components/Paging";


const ListProductsSalePage = () => {
  const [products, setProducts] = useState([]);
  const [count, setCount] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [postPerPage] = useState(5);
  const [indexOfLastPost, setIndexOfLastPost] = useState(0);
  const [indexOfFirstPost, setIndexOfFirstPost] = useState(0);
  const [currentPosts, setCurrentPosts] = useState(0);

  useEffect(() => {
    axios
      .get("/product-sale-join")
      .then((res) => {
        setProducts(res.data);
      })
      .catch((error) => {
        console.log("error", error);
      });
    setCount(products.length);
    setIndexOfLastPost(currentPage * postPerPage);
    setIndexOfFirstPost(indexOfLastPost - postPerPage);
    setCurrentPosts(products.slice(indexOfFirstPost, indexOfLastPost));
  }, [currentPage, indexOfLastPost, indexOfFirstPost, products, postPerPage]);

  const setPage = (error) => {
    setCurrentPage(error);
  };


  return (
    <div style={{ marginBottom: 150 }}>
      {currentPosts && products.length > 0 ? (
        currentPosts.map((productData, idx) => (
          <Card key={idx} sx={{ minWidth: 275 }} variant="outlined">
            <CardContent>
              <Typography variant="h5" component="div">
                id: {productData.goods_id}, name : {productData.goods_nm}
              </Typography>
              <Typography variant="body2">
                stat : {productData.stat}
                <br />
                total_amt : {productData.total_cnt}
                <br />
                order_fee : {productData.ordr_fee}
                <br />
                trade_fee : {productData.trade_fee}
                <br />
                created_dt : {productData.created_dt}
                <br />
                created_by : {productData.created_by}
                <br />
                sale_cnt : {productData.sale_cnt}
              </Typography>
              <br />
              <br />
              <Grid container spacing={2}>
                <Grid item={true} xs={3}>
                  <Typography variant="body2">판매율 :</Typography>
                </Grid>
                <Grid item={true} xs={9}>
                  {/* <ProgressBar /> */}
                  <Box sx={{ width: "100%" }}>
                    <ProgressBar value={productData.sale_rate} />
                  </Box>
                </Grid>
              </Grid>
            </CardContent>
            <Divider />
            <CardActions>
              <Link to={`/order/${productData.goods_id}`}>구매하기</Link>
              {/* <Button size="large" onClick={navigateToOrder}>
              구매하기
            </Button> */}
            </CardActions>
          </Card>
        ))
      ) : (
        <div> No posts.</div>
      )}
      <Paging page={currentPage} count={count} setPage={setPage} />
    </div>
  );
};

export default ListProductsSalePage;

 

실행화면

 

참고 :

https://www.npmjs.com/package/react-js-pagination

https://velog.io/@eunjitech/react-js-pagination-pagination-%EA%B5%AC%ED%98%84%ED%95%98%EA%B8%B0

https://cotak.tistory.com/112

https://mui.com/material-ui/react-pagination/

 

 

 

 

 

댓글