ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Material UI를 사용하여 Pagination 적용하기
    React 2022. 11. 21. 12:48

    많은 데이터를 보여줘야 할 때, 가독성을 위해서 페이지를 나눠야할 필요가 있을 수 있다.

    Pagination을 통해서, 더 깔끔하게 사이트를 구성할 수 있다.

    Pagination 컴포넌트의 구현을 위해서 리액트 컴포넌트 라이브러리인 Material UI (mui)를 사용하였다.
    🍙 mui 설치 : npm install @mui/material @emotion/react @emotion/styled

    🍯 mui Pagination 사용 : https://mui.com/material-ui/react-pagination/#main-content
    🍯 mui에서는 division을 나누기 위해서 Stack를 사용한다.

     

    React Pagination component - Material UI

    The Pagination component enables the user to select a specific page from a range of pages.

    mui.com

    전체 코드

    import dummydata from "../asset/dummydata";
    import { Stack, Pagination } from "@mui/material";
    import IndividualData from "../component/IndividualData";
    import { Link } from "react-router-dom";
    import { useState, useEffect } from "react";
    
    const DataList = () => {
      const LAST_PAGE = dummydata.length % 10 === 0 ? 
      	parseInt(dummydata.length / 10) : parseInt(dummydata.length / 10) + 1; // 마지막 페이지
      const [page, setPage] = useState(1); // 처음 페이지는 1이다.
      const [data, setData] = useState(/* 처음 페이지의 데이터들 */);
    
      useEffect(() => {
          // setData(/* fetch(또는 전체 데이터에서 slice)로 현재 page의 데이터를 가져온다. */);
          // 한 페이지에 10개씩 보여준다.
          if(page === LAST_PAGE){ // 마지막 페이지는 데이터가 10개보다 부족할 수도 있다.
            setData(dummydata.slice(10 * (page - 1)));
          } else {
            setData(dummydata.slice(10 * (page - 1), 10 * (page - 1) + 10));
          }  
        }, [page]);
    
      const handlePage = (event) => {
        const nowPageInt = parseInt(event.target.outerText);
        setPage(nowPageInt);
      }
    
      return (
        <Stack alignItems="center">
          <Stack direction="row" justifyContent="center" sx={{ flexWrap: "wrap" }}>
            {data.map((el) => {
              return (
                <Stack
                  key={el.id}
                  alignItems="center"
                  textAlign="center"
                  sx={{
                    width: 450,
                    border: 1,
                    margin: 3,
                    padding: -0.1,
                    borderRadius: 4,
                    boxShadow: "1px 1.5px gray",
                    "&:hover": {
                      boxShadow: "2px 2px 2px 2px gray",
                      transform: "translate(-1px, -1px)",
                    },
                  }}
                >
                  <Link
                    to={`/list/${el.id}`}
                    style={{ textDecoration: "none", color: "black", width: "100%" }}
                  >
                    <IndividualData data={el} />
                  </Link>
                </Stack>
              );
            })}
          </Stack>
          <Pagination count={LAST_PAGE} defaultPage={1} boundaryCount={2} 
            color="primary" size="large" sx={{margin: 2}} onChange={(e) => handlePage(e)}/>
        </Stack>
      );
    };
    
    export default DataList;

    하나의 페이지에서 10개의 아이템을 보여주는 코드를 작성하였다.

     

    + 서버로부터 데이터를 요청할 때 pagination에 도움이 되는 툴로 react-query나 swr의 useInfinity 훅이 있다.

Designed by Tistory.