페이지네이션

페이지네이션 (Pagination)

Pagination 컴포넌트는 사용자가 여러 페이지 범위 중에서 특정 페이지를 선택할 수 있게 해 주는 컴포넌트예요.

출처: 문서

본문

기본 페이지네이션 (Basic pagination)

import Pagination from '@mui/material/Pagination';
import Stack from '@mui/material/Stack';

export default function BasicPagination() {
  return (
    <Stack spacing={2}>
      <Pagination count={10} />
      <Pagination count={10} color="primary" />
      <Pagination count={10} color="secondary" />
      <Pagination count={10} disabled />
    </Stack>
  );
}

아웃라인 페이지네이션 (Outlined pagination)

import Pagination from '@mui/material/Pagination';
import Stack from '@mui/material/Stack';

export default function PaginationOutlined() {
  return (
    <Stack spacing={2}>
      <Pagination count={10} variant="outlined" />
      <Pagination count={10} variant="outlined" color="primary" />
      <Pagination count={10} variant="outlined" color="secondary" />
      <Pagination count={10} variant="outlined" disabled />
    </Stack>
  );
}

라운드 페이지네이션 (Rounded pagination)

import Pagination from '@mui/material/Pagination';
import Stack from '@mui/material/Stack';

export default function PaginationRounded() {
  return (
    <Stack spacing={2}>
      <Pagination count={10} shape="rounded" />
      <Pagination count={10} variant="outlined" shape="rounded" />
    </Stack>
  );
}

페이지네이션 크기 (Pagination size)

import Pagination from '@mui/material/Pagination';
import Stack from '@mui/material/Stack';

export default function PaginationSize() {
  return (
    <Stack spacing={2}>
      <Pagination count={10} size="small" />
      <Pagination count={10} />
      <Pagination count={10} size="large" />
    </Stack>
  );
}

버튼 (Buttons)

선택적으로 첫 페이지와 마지막 페이지 버튼을 활성화하거나, 이전/다음 페이지 버튼을 비활성화할 수 있어요.

import Pagination from '@mui/material/Pagination';
import Stack from '@mui/material/Stack';

export default function PaginationButtons() {
  return (
    <Stack spacing={2}>
      <Pagination count={10} showFirstButton showLastButton />
      <Pagination count={10} hidePrevButton hideNextButton />
    </Stack>
  );
}

커스텀 아이콘 (Custom icons)

컨트롤 아이콘을 커스터마이징할 수 있어요.

import Pagination from '@mui/material/Pagination';
import PaginationItem from '@mui/material/PaginationItem';
import Stack from '@mui/material/Stack';
import ArrowBackIcon from '@mui/icons-material/ArrowBack';
import ArrowForwardIcon from '@mui/icons-material/ArrowForward';

export default function CustomIcons() {
  return (
    <Stack spacing={2}>
      <Pagination
        count={10}
        renderItem={(item) => (
          <PaginationItem
            slots={{ previous: ArrowBackIcon, next: ArrowForwardIcon }}
            {...item}
          />
        )}
      />
    </Stack>
  );
}

페이지네이션 범위 (Pagination ranges)

current page(현재 페이지) 양쪽에 표시할 자릿수는 siblingCount prop으로, 시작 및 끝 페이지 번호에 인접한 자릿수는 boundaryCount prop으로 지정할 수 있어요.

import Pagination from '@mui/material/Pagination';
import Stack from '@mui/material/Stack';

export default function PaginationRanges() {
  return (
    <Stack spacing={2}>
      <Pagination count={11} defaultPage={6} siblingCount={0} />
      <Pagination count={11} defaultPage={6} /> {/* Default ranges */}
      <Pagination count={11} defaultPage={6} siblingCount={0} boundaryCount={2} />
      <Pagination count={11} defaultPage={6} boundaryCount={2} />
    </Stack>
  );
}

제어(Controlled) 페이지네이션

import * as React from 'react';
import Typography from '@mui/material/Typography';
import Pagination from '@mui/material/Pagination';
import Stack from '@mui/material/Stack';

export default function PaginationControlled() {
  const [page, setPage] = React.useState(1);
  const handleChange = (event: React.ChangeEvent<unknown>, value: number) => {
    setPage(value);
  };

  return (
    <Stack spacing={2}>
      <Typography>Page: {page}</Typography>
      <Pagination count={10} page={page} onChange={handleChange} />
    </Stack>
  );
}

라우터 연동 (Router integration)

import { Link, MemoryRouter, Route, Routes, useLocation } from 'react-router';
import Pagination from '@mui/material/Pagination';
import PaginationItem from '@mui/material/PaginationItem';

function Content() {
  const location = useLocation();
  const query = new URLSearchParams(location.search);
  const page = parseInt(query.get('page') || '1', 10);
  return (
    <Pagination
      page={page}
      count={10}
      renderItem={(item) => (
        <PaginationItem
          component={Link}
          to={`/inbox${item.page === 1 ? '' : `?page=${item.page}`}`}
          {...item}
        />
      )}
    />
  );
}

export default function PaginationLink() {
  return (
    <MemoryRouter initialEntries={['/inbox']} initialIndex={0}>
      <Routes>
        <Route path="*" element={<Content />} />
      </Routes>
    </MemoryRouter>
  );
}

usePagination

고급 커스터마이징 사용 사례를 위해, 헤드리스(headless) usePagination() 훅이 노출되어 있어요. 이 훅은 Pagination 컴포넌트와 거의 같은 옵션을 받지만, JSX 렌더링과 관련된 모든 props는 제외돼요. Pagination 컴포넌트는 이 훅을 기반으로 만들어졌어요.

import usePagination from '@mui/material/usePagination';
import * as React from 'react';
import usePagination from '@mui/material/usePagination';
import { styled } from '@mui/material/styles';

const count = 10;

const List = styled('ul')({
  listStyle: 'none',
  padding: 0,
  margin: 0,
  display: 'flex',
});

export default function UsePagination() {
  const firstPageRef = React.useRef<HTMLButtonElement>(null);
  const lastPageRef = React.useRef<HTMLButtonElement>(null);

  const { items } = usePagination({
    count,
  });

  return (
    <nav>
      <List>
        {items.map(({ page, type, selected, onClick, ...item }, index) => {
          let children = null;

          if (type === 'start-ellipsis' || type === 'end-ellipsis') {
            children = '…';
          } else if (type === 'page') {
            let pageRef;

            if (page === 1) {
              pageRef = firstPageRef;
            } else if (page === count) {
              pageRef = lastPageRef;
            }

            children = (
              <button
                type="button"
                ref={pageRef}
                style={{
                  fontWeight: selected ? 'bold' : undefined,
                }}
                {...item}
                onClick={onClick}
              >
                {page}
              </button>
            );
          } else {
            children = (
              <button
                type="button"
                {...item}
                onClick={(event) => {
                  let focusTarget: typeof firstPageRef | undefined;

                  if (type === 'previous' && page === 1) {
                    focusTarget = firstPageRef;
                  } else if (type === 'next' && page === count) {
                    focusTarget = lastPageRef;
                  }

                  const shouldMoveFocus =
                    event.currentTarget.ownerDocument.activeElement ===
                    event.currentTarget;

                  onClick(event);

                  if (shouldMoveFocus) {
                    focusTarget?.current?.focus();
                  }
                }}
              >
                {type}
              </button>
            );
          }

          return <li key={index}>{children}</li>;
        })}
      </List>
    </nav>
  );
}

테이블 페이지네이션 (Table pagination)

Pagination 컴포넌트는 무한 로딩(infinite loading)을 사용하지 않을 때 임의의 항목 목록을 페이지네이션하도록 설계되었어요. SEO가 중요한 맥락, 예를 들어 블로그에서 선호됩니다.

대량의 테이블 형식 데이터의 페이지네이션에는 TablePagination 컴포넌트를 사용해야 합니다.

import * as React from 'react';
import TablePagination from '@mui/material/TablePagination';

export default function TablePaginationDemo() {
  const [page, setPage] = React.useState(2);
  const [rowsPerPage, setRowsPerPage] = React.useState(10);

  const handleChangePage = (
    event: React.MouseEvent<HTMLButtonElement> | null,
    newPage: number,
  ) => {
    setPage(newPage);
  };

  const handleChangeRowsPerPage = (
    event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>,
  ) => {
    setRowsPerPage(parseInt(event.target.value, 10));
    setPage(0);
  };

  return (
    <TablePagination
      component="div"
      count={100}
      page={page}
      onPageChange={handleChangePage}
      rowsPerPage={rowsPerPage}
      onRowsPerPageChange={handleChangeRowsPerPage}
    />
  );
}

:::warning Pagination의 page prop은 URL에 값을 포함해야 한다는 요구사항에 맞춰 1부터 시작하지만, TablePagination의 page prop은 대량의 테이블 데이터를 렌더링할 때 따라오는 0 기반(zero-based) JavaScript 배열 요구사항에 맞춰 0부터 시작한다는 점에 유의하세요. :::

이 사용 사례에 대해 더 자세히 알고 싶다면 문서의 테이블 섹션을 참고하세요.

접근성 (Accessibility)

ARIA

루트 노드는 기본적으로 역할 "navigation"과 aria-label "pagination navigation"을 가져요. 페이지 항목들은 항목의 목적을 식별하는 aria-label("go to first page", "go to previous page", "go to page 1" 등)을 가집니다. getItemAriaLabel prop을 사용해 이들을 오버라이드할 수 있어요.

키보드 (Keyboard)

페이지네이션 항목들은 tabindex "0"으로 탭 순서에 위치해요.

Pagination API

데모 (Demos)

이 React 컴포넌트의 사용 예시와 자세한 내용은 컴포넌트 데모 페이지를 방문해 보세요:

Import

import Pagination from '@mui/material/Pagination';
// or
import { Pagination } from '@mui/material';

Props

이름 (Name) 타입 (Type) 기본값 (Default) 필수 (Required) 설명 (Description)
boundaryCount integer 1 No
classes object - No Override or extend the styles applied to the component.
color 'primary' | 'secondary' | 'standard' | string 'standard' No
count integer 1 No
defaultPage integer 1 No
disabled bool false No
getItemAriaLabel function(type: string, page: number | null, selected: boolean) => string - No
hideNextButton bool false No
hidePrevButton bool false No
onChange function(event: React.ChangeEvent<unknown>, page: number) => void - No
page integer - No
renderItem function(params: PaginationRenderItemParams) => ReactNode (item) => <PaginationItem {...item} /> No
shape 'circular' | 'rounded' 'circular' No
showFirstButton bool false No
showLastButton bool false No
siblingCount integer 1 No
size 'small' | 'medium' | 'large' | string 'medium' No
sx Array<func | object | bool> | func | object - No The system prop that allows defining system overrides as well as additional CSS styles.
variant 'outlined' | 'text' | string 'text' No

참고 (Note): ref는 루트 요소(HTMLElement)로 전달됩니다.

제공된 다른 모든 props는 루트 요소(네이티브 요소)로 전달됩니다.

테마 기본 props (Theme default props)

MuiPagination를 사용해 테마로 이 컴포넌트의 기본 props를 변경할 수 있어요.

CSS

규칙 이름 (Rule name)

전역 클래스 (Global class) 규칙 이름 (Rule name) 설명 (Description)
- outlined Styles applied to the root element if variant="outlined".
- root Styles applied to the root element.
- text Styles applied to the root element if variant="text".
- ul Styles applied to the ul element.

소스 코드 (Source code)

이 페이지에서 필요한 정보를 찾지 못했다면, 컴포넌트의 구현을 살펴보면서 더 자세한 내용을 확인해 보세요.

PaginationItem API

데모 (Demos)

이 React 컴포넌트의 사용 예시와 자세한 내용은 컴포넌트 데모 페이지를 방문해 보세요:

Import

import PaginationItem from '@mui/material/PaginationItem';
// or
import { PaginationItem } from '@mui/material';

Props

이름 (Name) 타입 (Type) 기본값 (Default) 필수 (Required) 설명 (Description)
classes object - No Override or extend the styles applied to the component.
color 'primary' | 'secondary' | 'standard' | string 'standard' No
component elementType - No
disabled bool false No
nativeButton bool - No
page node - No
selected bool false No
shape 'circular' | 'rounded' 'circular' No
size 'small' | 'medium' | 'large' | string 'medium' No
slotProps { first?: func | object, last?: func | object, next?: func | object, previous?: func | object } {} No
slots { first?: elementType, last?: elementType, next?: elementType, previous?: elementType } {} No
sx Array<func | object | bool> | func | object - No The system prop that allows defining system overrides as well as additional CSS styles.
type 'end-ellipsis' | 'first' | 'last' | 'next' | 'page' | 'previous' | 'start-ellipsis' 'page' No
variant 'outlined' | 'text' | string 'text' No

참고 (Note): ref는 루트 요소(HTMLButtonElement)로 전달됩니다.

제공된 다른 모든 props는 루트 요소(ButtonBase)로 전달됩니다.

상속 (Inheritance)

위에 명시적으로 문서화되진 않았지만, ButtonBase 컴포넌트의 props는 PaginationItem에서도 사용할 수 있어요.

테마 기본 props (Theme default props)

MuiPaginationItem를 사용해 테마로 이 컴포넌트의 기본 props를 변경할 수 있어요.

슬롯 (Slots)

이름 (Name) 기본값 (Default) 클래스 (Class) 설명 (Description)
first FirstPageIcon - The component that renders the first page slot.
last LastPageIcon - The component that renders the last page slot.
next NavigateNextIcon - The component that renders the next page slot.
previous NavigateBeforeIcon - The component that renders the previous page slot.

CSS

규칙 이름 (Rule name)

전역 클래스 (Global class) 규칙 이름 (Rule name) 설명 (Description)
- colorPrimary Styles applied to the root element if color="primary".
- colorSecondary Styles applied to the root element if color="secondary".
.Mui-disabled - State class applied to the root element if disabled={true}.
- ellipsis Styles applied to the root element if type="start-ellipsis" or type="end-ellipsis".
- firstLast Styles applied to the root element if type="first" or type="last".
.Mui-focusVisible - State class applied to the root element if keyboard focused.
- icon Styles applied to the icon to display.
- outlined Styles applied to the root element if variant="outlined".
- page Styles applied to the root element if type="page".
- previousNext Styles applied to the root element if type="previous" or type="next".
- root Styles applied to the root element.
- rounded Styles applied to the root element if rounded="true".
.Mui-selected - State class applied to the root element if selected={true}.
- sizeLarge Styles applied to the root element if size="large".
- sizeSmall Styles applied to the root element if size="small".
- text Styles applied to the root element if variant="text".

소스 코드 (Source code)

이 페이지에서 필요한 정보를 찾지 못했다면, 컴포넌트의 구현을 살펴보면서 더 자세한 내용을 확인해 보세요.

TablePagination API

데모 (Demos)

이 React 컴포넌트의 사용 예시와 자세한 내용은 컴포넌트 데모 페이지를 방문해 보세요:

Import

import TablePagination from '@mui/material/TablePagination';
// or
import { TablePagination } from '@mui/material';

Props

이름 (Name) 타입 (Type) 기본값 (Default) 필수 (Required) 설명 (Description)
count integer - Yes
onPageChange function(event: React.MouseEvent<HTMLButtonElement> | null, page: number) => void - Yes
page integer - Yes
rowsPerPage integer - Yes
ActionsComponent elementType TablePaginationActions No
classes object - No Override or extend the styles applied to the component.
component elementType - No
disabled bool false No
getItemAriaLabel function(type: string) => string `function defaultGetAriaLabel(type) {
return Go to ${type} page;
}` No
labelDisplayedRows func `function defaultLabelDisplayedRows({ from, to, count }) {
return ${formatNumber(from)}–${formatNumber(to)} of ${count !== -1 ? formatNumber(count) : more than ${formatNumber(to)}};
}` No
labelRowsPerPage node 'Rows per page:' No
onRowsPerPageChange function(event: React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>) => void - No
rowsPerPageOptions Array<number | { label: string, value: number }> [10, 25, 50, 100] No
showFirstButton bool false No
showLastButton bool false No
slotProps { actions?: { firstButton?: object, firstButtonIcon?: object, lastButton?: object, lastButtonIcon?: object, nextButton?: object, nextButtonIcon?: object, previousButton?: object, previousButtonIcon?: object }, displayedRows?: func | object, menuItem?: func | object, root?: func | object, select?: object, selectLabel?: func | object, spacer?: func | object, toolbar?: func | object } {} No
slots { actions?: { firstButton?: elementType, firstButtonIcon?: elementType, lastButton?: elementType, lastButtonIcon?: elementType, nextButton?: elementType, nextButtonIcon?: elementType, previousButton?: elementType, previousButtonIcon?: elementType }, displayedRows?: elementType, menuItem?: elementType, root?: elementType, select?: elementType, selectLabel?: elementType, spacer?: elementType, toolbar?: elementType } {} No
sx Array<func | object | bool> | func | object - No The system prop that allows defining system overrides as well as additional CSS styles.

참고 (Note): ref는 루트 요소(HTMLTableCellElement)로 전달됩니다.

제공된 다른 모든 props는 루트 요소(TableCell)로 전달됩니다.

상속 (Inheritance)

위에 명시적으로 문서화되진 않았지만, TableCell 컴포넌트의 props는 TablePagination에서도 사용할 수 있어요.

테마 기본 props (Theme default props)

MuiTablePagination를 사용해 테마로 이 컴포넌트의 기본 props를 변경할 수 있어요.

슬롯 (Slots)

이름 (Name) 기본값 (Default) 클래스 (Class) 설명 (Description)
root TableCell .MuiTablePagination-root The component that renders the root slot.
Follow this guide to learn more about the requirements for this component.
toolbar Toolbar .MuiTablePagination-toolbar The component that renders the toolbar slot.
Follow this guide to learn more about the requirements for this component.
spacer 'div' .MuiTablePagination-spacer The tag that renders the spacer slot.
selectLabel 'p' .MuiTablePagination-selectLabel The tag that renders the selectLabel slot.
select Select .MuiTablePagination-select The component that renders the select slot.
Follow this guide to learn more about the requirements for this component.
menuItem MenuItem .MuiTablePagination-menuItem The component that renders the select slot.
Follow this guide to learn more about the requirements for this component.
displayedRows 'p' .MuiTablePagination-displayedRows The tag that renders the displayedRows slot.
actions undefined .MuiTablePagination-actions The slots that passed to the actions slot.

CSS

규칙 이름 (Rule name)

전역 클래스 (Global class) 규칙 이름 (Rule name) 설명 (Description)
- input Styles applied to the Select component root element.
- selectIcon Styles applied to the Select component icon class.
- selectRoot Styles applied to the Select component root element.

소스 코드 (Source code)

이 페이지에서 필요한 정보를 찾지 못했다면, 컴포넌트의 구현을 살펴보면서 더 자세한 내용을 확인해 보세요.

TablePaginationActions API

데모 (Demos)

이 React 컴포넌트의 사용 예시와 자세한 내용은 컴포넌트 데모 페이지를 방문해 보세요:

Import

import TablePaginationActions from '@mui/material/TablePaginationActions';
// or
import { TablePaginationActions } from '@mui/material';

Props

이름 (Name) 타입 (Type) 기본값 (Default) 필수 (Required) 설명 (Description)
getItemAriaLabel function(type: string) => string - Yes
classes object - No Override or extend the styles applied to the component.
disabled bool false No

참고 (Note): ref는 루트 요소(HTMLDivElement)로 전달됩니다.

제공된 다른 모든 props는 루트 요소(네이티브 요소)로 전달됩니다.

테마 기본 props (Theme default props)

MuiTablePaginationActions를 사용해 테마로 이 컴포넌트의 기본 props를 변경할 수 있어요.

슬롯 (Slots)

이름 (Name) 기본값 (Default) 클래스 (Class) 설명 (Description)
firstButton IconButton - The component that renders the first button.
lastButton IconButton - The component that renders the last button.
nextButton IconButton - The component that renders the next button.
previousButton IconButton - The component that renders the previous button.
firstButtonIcon FirstPageIcon - The component that renders the first button icon.
lastButtonIcon LastPageIcon - The component that renders the last button icon.
nextButtonIcon KeyboardArrowRight - The component that renders the next button icon.
previousButtonIcon KeyboardArrowLeft - The component that renders the previous button icon.

소스 코드 (Source code)

이 페이지에서 필요한 정보를 찾지 못했다면, 컴포넌트의 구현을 살펴보면서 더 자세한 내용을 확인해 보세요.

더 알아보기 (Learn more)