Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

냥냠

[React] Pagination 구현하기(mui) 본문

React

[React] Pagination 구현하기(mui)

sueeee-e 2024. 8. 23. 16:00

pagination을 구현하기 위한 방법 

 

1. mui - pagination

 

mui의 <Pagination> 컴포넌트는 페이지네이션을 위한 UI만 제공하고

데이터를 페이지별로 나누는 로직은 별도로 구현해줘야 한다.

 


🍄 간단한 pagination 로직 🍄

 

- 한 페이지 당 표시되는 게시물 개수 : a

- 총 게시물 개수 : N

 

이 정보가 있으면 N / a 의 몫을 반올림하면 총 페이지의 개수까지 구해진다. 

 

페이지 번호를 기준으로 표시해줘야 할 게시물들의 범위 ( 해당 페이지의 첫 게시물의 위치 ) 

예를 들어

1번째 페이지의 첫 게시물의 위치는 (1 - 1) * a = 0

2번째 페이지의 첫 게시물의 위치는 (2 - 1) *a = a

3번째 페이지 => 2a, 4번째 페이지 => 3a  ... 


 

현재 페이지 상태 관리 ( useState )

한 페이지 당 표시되는 게시물 개수 정해주기

const [ currentPage, useCurrentPage ] = useState(1);
const itemsPerPage = 4;

 

 

전체 페이지 개수 계산 

const totalPages = Math.ceil(movies.results.length / itemPerPage); // 전체 게시물 / 페이지 당 게시물

 

해당 페이지의 첫 게시물과 마지막 게시물의 위치(인덱스)

slice를 이용하여 현재 페이지에 해당하는 게시물만 추출

const startIndex = (currentPage - 1) *itemsPerPage;
const endIndex = startIndex + itemsPerPage;
const currentMovies = movies.results.slice(startIndex, endIndex);

 

그리고 페이지 변경 시 호출될 함수까지 해주면 완성

const handlePageChange = (event, value) => {
	setCurrentPage(value);
  };
<Pagination
    count={totalPages} // 총 페이지 수
    page={currentPage} // 현재 페이지
    onChange={handlePageChange} // 페이지 변경 핸들러
/>

 


실제 코드 

const MovieSlide2 = ({ movies }) => {
    const [currentPage, setCurrentPage] = useState(1);
    const itemsPerPage = 4;

    // 페이지 변경 시 호출될 함수
    const handlePageChange = (event, value) => {
        setCurrentPage(value);
    };

    if (!movies || !movies.results) {
        return <div>Movies data is not available.</div>; // 데이터가 없을 때 보여줄 메시지
    }

    // 전체 영화 리스트에서 현재 페이지에 해당하는 영화들만 추출
    const startIndex = (currentPage - 1) * itemsPerPage;
    const endIndex = startIndex + itemsPerPage;
    const currentMovies = movies.results.slice(startIndex, endIndex);

    // 전체 페이지 수 계산
    const totalPages = Math.ceil(movies.results.length / itemsPerPage);


    return (
        <div>
            <Box sx={{ flexGrow: 1 }}>
                <Grid container spacing={3} columns={2}>
                    {currentMovies.map((item) => (
                        <Grid item xs={1} key={item.id}>
                            <MovieCard2 item={item} />
                        </Grid>
                    ))}
                </Grid>
            </Box>
           
            <Box sx={{ display: 'flex', justifyContent: 'center', marginTop: '20px' }}>
                <Pagination
                    count={totalPages} // 총 페이지 수
                    page={currentPage} // 현재 페이지
                    onChange={handlePageChange} // 페이지 변경 핸들러
                    size='large'
                    sx={{
                        '& .MuiPaginationItem-root': {
                            color: 'white', // 기본 숫자 색상
                        },
                        '& .Mui-selected': {
                            color: 'white', // 선택된 페이지의 숫자 색상
                            backgroundColor: 'red', // 선택된 페이지의 배경색
                        },
                    }}
                />
            </Box>
       
        </div>
    );
}

 

 

구현 화면


참고

https://www.daleseo.com/react-pagination/

 

React로 페이지네이션 UI 구현하기

Engineering Blog by Dale Seo

www.daleseo.com