본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

Data Grid - 페이지네이션

원문 보기 위키 갱신

Data Grid - 페이지네이션 (Pagination)

행을 쉽게 페이지로 나누고 필요한 것만 가져와봐요.

출처: MUI X documentation

본문

페이지네이션 활성화하기 (Enabling pagination)

기본 페이지네이션 동작은 요금제(plan)에 따라 달라져요:

:::info 내보낸 CSV 및 Excel 파일은 기본적으로 페이지네이션을 무시하고 모든 데이터를 포함해요. 내보낸 파일에 페이지네이션을 적용하려면 사용 가능한 행 선택기를 검토하세요. :::

Community 요금제 (Community plan)

Community Data Grid의 경우 페이지네이션은 기본적으로 활성화되어 있으며 비활성화할 수 없어요.

import { DataGrid } from '@mui/x-data-grid';
import { useDemoData } from '@mui/x-data-grid-generator';

export default function PaginationCommunityNoSnap() {
  const { data, loading } = useDemoData({
    dataSet: 'Commodity',
    rowLength: 500,
    maxColumns: 6,
  });

  return (
    <div style={{ height: 300, width: '100%' }}>
      <DataGrid {...data} loading={loading} />
    </div>
  );
}

Pro 및 Premium

Pro 및 Premium Data Grid의 경우 페이지네이션은 기본적으로 비활성화되어 있어요. 활성화하려면 pagination prop을 사용하세요.

import { DataGridPremium, GridColDef, GridRowsProp } from '@mui/x-data-grid-premium';

const rows: GridRowsProp = [
  {
    jobTitle: 'Head of Human Resources',
    recruitmentDate: new Date(2020, 8, 12),
    contract: 'full time',
    id: 0,
  },
  {
    jobTitle: 'Head of Sales',
    recruitmentDate: new Date(2017, 3, 4),
    contract: 'full time',
    id: 1,
  },
  {
    jobTitle: 'Sales Person',
    recruitmentDate: new Date(2020, 11, 20),
    contract: 'full time',
    id: 2,
  },
  {
    jobTitle: 'Sales Person',
    recruitmentDate: new Date(2020, 10, 14),
    contract: 'part time',
    id: 3,
  },
  {
    jobTitle: 'Sales Person',
    recruitmentDate: new Date(2017, 10, 29),
    contract: 'part time',
    id: 4,
  },
  {
    jobTitle: 'Sales Person',
    recruitmentDate: new Date(2020, 7, 21),
    contract: 'full time',
    id: 5,
  },
  {
    jobTitle: 'Sales Person',
    recruitmentDate: new Date(2020, 7, 20),
    contract: 'intern',
    id: 6,
  },
  {
    jobTitle: 'Sales Person',
    recruitmentDate: new Date(2019, 6, 28),
    contract: 'full time',
    id: 7,
  },
  {
    jobTitle: 'Head of Engineering',
    recruitmentDate: new Date(2016, 3, 14),
    contract: 'full time',
    id: 8,
  },
  {
    jobTitle: 'Tech lead front',
    recruitmentDate: new Date(2016, 5, 17),
    contract: 'full time',
    id: 9,
  },
  {
    jobTitle: 'Front-end developer',
    recruitmentDate: new Date(2019, 11, 7),
    contract: 'full time',
    id: 10,
  },
  {
    jobTitle: 'Tech lead devops',
    recruitmentDate: new Date(2021, 7, 1),
    contract: 'full time',
    id: 11,
  },
  {
    jobTitle: 'Tech lead back',
    recruitmentDate: new Date(2017, 0, 12),
    contract: 'full time',
    id: 12,
  },
  {
    jobTitle: 'Back-end developer',
    recruitmentDate: new Date(2019, 2, 22),
    contract: 'intern',
    id: 13,
  },
  {
    jobTitle: 'Back-end developer',
    recruitmentDate: new Date(2018, 4, 19),
    contract: 'part time',
    id: 14,
  },
];

const columns: GridColDef[] = [
  { field: 'jobTitle', headerName: 'Job Title', width: 200, rowHeader: true },
  {
    field: 'recruitmentDate',
    headerName: 'Recruitment Date',
    type: 'date',
    width: 150,
  },
  {
    field: 'contract',
    headerName: 'Contract Type',
    type: 'singleSelect',
    valueOptions: ['full time', 'part time', 'intern'],
    width: 150,
  },
];

export default function PageSizeAutoPremium() {
  return (
    <div style={{ height: 320, width: '100%' }}>
      <DataGridPremium pagination rows={rows} columns={columns} autoPageSize />
    </div>
  );
}

페이지 크기 (Size of the page)

Data Grid(MIT 라이선스)는 최대 100개의 행이 있는 페이지로 제한돼요. 더 큰 페이지를 원하면 Pro 요금제 이상으로 업그레이드해야 해요.

기본적으로 각 페이지에는 100개의 행이 포함돼요. 사용자는 푸터의 선택기를 통해 페이지 크기를 바꿀 수 있어요.

페이지 크기 옵션 (Page size options)

pageSizeOptions prop을 사용해 "Rows per page" 선택기에 표시되는 옵션을 커스터마이즈할 수 있어요. 항목의 배열을 제공해야 하며, 각 항목은 다음 유형 중 하나여야 해요:

  • number, 각 숫자는 옵션의 레이블과 값으로 사용돼요.

    <DataGrid pageSizeOptions={[5, 10, 25]}>
    
  • object, value와 label 키가 각각 옵션의 값과 레이블로 사용돼요. 모든 결과를 표시하려면 value를 -1로 정의하세요.

    <DataGrid pageSizeOptions={[10, 100, { value: 1000, label: '1,000' }, { value: -1, label: 'All' }]}>
    
import { DataGrid } from '@mui/x-data-grid';
import { useDemoData } from '@mui/x-data-grid-generator';

export default function PageSizeCustomOptions() {
  const { data, loading } = useDemoData({
    dataSet: 'Commodity',
    rowLength: 100,
    maxColumns: 6,
  });

  return (
    <div style={{ height: 400, width: '100%' }}>
      <DataGrid
        {...data}
        loading={loading}
        initialState={{
          ...data.initialState,
          pagination: { paginationModel: { pageSize: 5 } },
        }}
        pageSizeOptions={[5, 10, 25, { value: -1, label: 'All' }]}
      />
    </div>
  );
}

자동 페이지 크기 (Automatic page size)

autoPageSize prop을 사용해 컨테이너 높이와 세로 스크롤 바 없이 표시할 수 있는 최대 행 수에 맞게 pageSize를 자동으로 조정할 수 있어요.

:::warning autoHeight는 Data Grid의 높이를 pageSize에 따라 조정하므로 autoPageSize와 autoHeight prop을 동시에 사용할 수 없어요. :::

import * as React from 'react';
import { DataGrid } from '@mui/x-data-grid';
import { useDemoData } from '@mui/x-data-grid-generator';
import Stack from '@mui/material/Stack';
import MenuItem from '@mui/material/MenuItem';
import FormControl from '@mui/material/FormControl';
import InputLabel from '@mui/material/InputLabel';
import Select from '@mui/material/Select';

export default function PageSizeAuto() {
  const { data, loading } = useDemoData({
    dataSet: 'Commodity',
    rowLength: 100,
    maxColumns: 6,
  });

  const [height, setHeight] = React.useState(400);

  return (
    <Stack style={{ width: '100%' }} spacing={2} sx={{ alignItems: 'flex-start' }}>
      <FormControl fullWidth>
        <InputLabel htmlFor="height-of-container" id="height-of-container-label">
          Height of the container
        </InputLabel>
        <Select
          label="Main Grouping Criteria"
          onChange={(event) => setHeight(Number(event.target.value))}
          value={height}
          id="height-of-container"
          labelId="height-of-container-label"
        >
          <MenuItem value="300">300px</MenuItem>
          <MenuItem value="400">400px</MenuItem>
          <MenuItem value="500">500px</MenuItem>
        </Select>
      </FormControl>
      <div style={{ height, width: '100%' }}>
        <DataGrid autoPageSize {...data} loading={loading} />
      </div>
    </Stack>
  );
}

페이지네이션 모델 (Pagination model)

페이지네이션 모델은 현재 페이지와 페이지 크기를 담은 객체예요. 기본값은 { page: 0, pageSize: 100 }이에요. 기본값을 바꾸려면 paginationModel prop으로 제어하거나 initialState.pagination.paginationModel로 커스텀 값을 초기화하세요.

페이지네이션 모델 초기화하기 (Initializing the pagination model)

제어하지 않고 페이지네이션 모델을 초기화하려면 initialState prop에 paginationModel을 제공하세요. 속성 중 하나에 값을 제공하지 않으면 기본값이 사용돼요.

<DataGrid
  initialState={{
    pagination: {
      paginationModel: { pageSize: 25, page: 0 },
    },
  }}
/>
import { DataGrid } from '@mui/x-data-grid';
import { useDemoData } from '@mui/x-data-grid-generator';

export default function PaginationModelInitialState() {
  const { data, loading } = useDemoData({
    dataSet: 'Commodity',
    rowLength: 500,
    maxColumns: 6,
  });

  return (
    <div style={{ height: 400, width: '100%' }}>
      <DataGrid
        {...data}
        loading={loading}
        initialState={{
          ...data.initialState,
          pagination: {
            ...data.initialState?.pagination,
            paginationModel: {
              pageSize: 25,
              /* page: 0 // default value will be used if not passed */
            },
          },
        }}
      />
    </div>
  );
}

제어된 페이지네이션 모델 (Controlled pagination model)

paginationModel prop을 전달해 그리드의 크기와 현재 페이지를 제어할 수 있어요. onPaginationModelChange prop을 사용해 paginationModel의 변경을 듣고 그에 따라 prop을 업데이트할 수 있어요.

const [paginationModel, setPaginationModel] = React.useState({
  pageSize: 25,
  page: 0,
});

<DataGrid
  paginationModel={paginationModel}
  onPaginationModelChange={setPaginationModel}
/>;
import * as React from 'react';
import { DataGrid } from '@mui/x-data-grid';
import { useDemoData } from '@mui/x-data-grid-generator';

export default function PaginationModelControlled() {
  const { data, loading } = useDemoData({
    dataSet: 'Commodity',
    rowLength: 500,
    maxColumns: 6,
  });
  const [paginationModel, setPaginationModel] = React.useState({
    pageSize: 25,
    page: 0,
  });

  return (
    <div style={{ height: 400, width: '100%' }}>
      <DataGrid
        paginationModel={paginationModel}
        onPaginationModelChange={setPaginationModel}
        {...data}
        loading={loading}
      />
    </div>
  );
}

서버 측 페이지네이션 (Server-side pagination)

기본적으로 페이지네이션은 클라이언트에서 처리돼요. 즉 모든 페이지의 행을 Data Grid에 제공해야 한다는 뜻이에요. 데이터셋이 너무 크고 페이지를 요청에 따라 가져오고 싶다면 서버 측 페이지네이션을 사용할 수 있어요.

:::warning 다른 서버 측 기능 없이 서버 측 페이지네이션을 활성화하면, Data Grid는 필터링과 정렬을 위한 부분적인 데이터만 제공받게 돼요. 전체 데이터셋으로 작업하려면 서버 측 필터링과 서버 측 정렬도 구현해야 해요. 아래 데모가 정확히 그것을 해요. :::

import * as React from 'react';
import { DataGrid, GridSortModel, GridFilterModel } from '@mui/x-data-grid';
import { createFakeServer } from '@mui/x-data-grid-generator';

const SERVER_OPTIONS = {
  useCursorPagination: false,
};

const { useQuery, ...data } = createFakeServer({}, SERVER_OPTIONS);

export default function ServerPaginationFilterSortGrid() {
  const [paginationModel, setPaginationModel] = React.useState({
    page: 0,
    pageSize: 5,
  });
  const [sortModel, setSortModel] = React.useState<GridSortModel>([]);
  const [filterModel, setFilterModel] = React.useState<GridFilterModel>({
    items: [],
  });
  const queryOptions = React.useMemo(
    () => ({ ...paginationModel, sortModel, filterModel }),
    [paginationModel, sortModel, filterModel],
  );
  const { isLoading, rows, pageInfo } = useQuery(queryOptions);

  // Some API clients return undefined while loading
  // Following lines are here to prevent `rowCount` from being undefined during the loading
  const rowCountRef = React.useRef(pageInfo?.totalRowCount || 0);

  const rowCount = React.useMemo(() => {
    if (pageInfo?.totalRowCount !== undefined) {
      rowCountRef.current = pageInfo.totalRowCount;
    }
    return rowCountRef.current;
  }, [pageInfo?.totalRowCount]);

  return (
    <div style={{ height: 400, width: '100%' }}>
      <DataGrid
        rows={rows}
        {...data}
        rowCount={rowCount}
        loading={isLoading}
        pageSizeOptions={[5]}
        paginationModel={paginationModel}
        sortModel={sortModel}
        filterModel={filterModel}
        paginationMode="server"
        sortingMode="server"
        filterMode="server"
        onPaginationModelChange={setPaginationModel}
        onSortModelChange={setSortModel}
        onFilterModelChange={setFilterModel}
      />
    </div>
  );
}

일반적으로 서버 측 페이지네이션은 두 가지 유형으로 분류할 수 있어요:

  • 인덱스 기반 페이지네이션(Index-based pagination)
  • 커서 기반 페이지네이션(Cursor-based pagination)

:::info 자세한 내용은 Selection—Usage with server-side pagination을 참고하세요. :::

인덱스 기반 페이지네이션 (Index-based pagination)

인덱스 기반 페이지네이션은 page와 pageSize를 사용해 서버에서 페이지별로 데이터를 가져와요.

서버 측 페이지네이션을 활성화하려면:

  • paginationMode prop을 server로 설정하세요
  • onPaginationModelChange prop을 사용해 페이지 변경에 반응하고 서버에서 데이터를 불러오세요

서버 측 페이지네이션은 전체 행 수 또는 rowCount의 가용성에 따라 하위 유형으로 더 세분화할 수 있어요.

Data Grid는 rowCount를 사용해 페이지 수를 계산하고 푸터에 페이지네이션의 현재 상태에 대한 정보를 표시해요. rowCount를 다음 방법 중 하나로 제공할 수 있어요:

  • 초기화(Initialize). initialState.pagination.rowCount prop을 사용해 rowCount를 초기화해요.
  • 제어(Control). rowCount prop을 onRowCountChange와 함께 사용해 rowCount를 제어하고, 행 수가 업데이트될 때 변경 사항을 반영해요.
  • API로 설정(Set using the API). Grid가 초기화된 후 apiRef.current.setRowCount 메서드를 사용해 rowCount를 설정해요.

서버 측에서 rowCount의 가용성에는 세 가지 서로 다른 가능성이 있을 수 있어요:

  1. 행 수를 사용할 수 있음(알려짐, known)
  2. 행 수를 사용할 수 없음(알 수 없음, unknown)
  3. 행 수를 사용할 수 있지만 정확하지 않고 나중에 업데이트될 수 있음(추정, estimated)

:::warning rowCount prop은 서버 측 페이지네이션 모드에서 데이터셋의 총 행 수를 DataGrid에 알리는 데 사용돼요. paginationMode가 client로 설정된 경우, 즉 페이지네이션이 클라이언트 측에서 처리될 때는 이 prop이 무시돼요. :::

위 시나리오를 처리하려면 rowCount, paginationMeta.hasNextPage, estimatedRowCount props를 구성할 수 있어요.

rowCount paginationMeta.hasNextPage estimatedRowCount
행 수 알려짐 (Known) number — —
행 수 알 수 없음 (Unknown) -1 boolean —
행 수 추정 (Estimated) -1 boolean number

알려진 행 수 (Known row count)

실제 행 수를 알 때 이 경우를 처리하려면 위 표에서 설명한 대로 props를 Data Grid에 전달하세요. 다음 예제가 그 방식을 보여줘요.

import * as React from 'react';
import { DataGrid } from '@mui/x-data-grid';
import { createFakeServer } from '@mui/x-data-grid-generator';

const SERVER_OPTIONS = {
  useCursorPagination: false,
};

const { useQuery, ...data } = createFakeServer({}, SERVER_OPTIONS);

export default function ServerPaginationGrid() {
  const [paginationModel, setPaginationModel] = React.useState({
    page: 0,
    pageSize: 5,
  });

  const { isLoading, rows, pageInfo } = useQuery(paginationModel);

  // Some API clients return undefined while loading
  // Following lines are here to prevent `rowCount` from being undefined during the loading
  const rowCountRef = React.useRef(pageInfo?.totalRowCount || 0);

  const rowCount = React.useMemo(() => {
    if (pageInfo?.totalRowCount !== undefined) {
      rowCountRef.current = pageInfo.totalRowCount;
    }
    return rowCountRef.current;
  }, [pageInfo?.totalRowCount]);

  return (
    <div style={{ height: 400, width: '100%' }}>
      <DataGrid
        rows={rows}
        {...data}
        rowCount={rowCount}
        loading={isLoading}
        pageSizeOptions={[5]}
        paginationModel={paginationModel}
        paginationMode="server"
        onPaginationModelChange={setPaginationModel}
      />
    </div>
  );
}

:::warning 로딩 중에 rowCount 값이 undefined가 되면 페이지가 0으로 재설정돼요. 이 문제를 피하려면 rowCount 값을 메모이즈해 로딩 중에 변하지 않도록 할 수 있어요:

const rowCountRef = React.useRef(pageInfo?.totalRowCount || 0);

const rowCount = React.useMemo(() => {
  if (pageInfo?.totalRowCount !== undefined) {
    rowCountRef.current = pageInfo.totalRowCount;
  }
  return rowCountRef.current;
}, [pageInfo?.totalRowCount]);

<DataGrid rowCount={rowCount} />;

:::

알 수 없는 행 수 (Unknown row count)

실제 행 수를 모를 때 이 경우를 처리하려면 위 표에서 설명한 대로 props를 Data Grid에 전달하세요. 다음 예제가 그 방식을 보여줘요.

import * as React from 'react';
import { DataGrid, GridPaginationMeta, useGridApiRef } from '@mui/x-data-grid';
import { createFakeServer } from '@mui/x-data-grid-generator';

const SERVER_OPTIONS = {
  useCursorPagination: false,
};

const rowLength = 98;

const { useQuery, ...data } = createFakeServer({ rowLength }, SERVER_OPTIONS);

export default function ServerPaginationGridNoRowCount() {
  const apiRef = useGridApiRef();
  const [paginationModel, setPaginationModel] = React.useState({
    page: 0,
    pageSize: 5,
  });

  const {
    isLoading,
    rows,
    pageInfo: { hasNextPage },
  } = useQuery(paginationModel);

  const paginationMetaRef = React.useRef<GridPaginationMeta>(undefined);

  // Memoize to avoid flickering when the `hasNextPage` is `undefined` during refetch
  const paginationMeta = React.useMemo(() => {
    if (
      hasNextPage !== undefined &&
      paginationMetaRef.current?.hasNextPage !== hasNextPage
    ) {
      paginationMetaRef.current = { hasNextPage };
    }
    return paginationMetaRef.current;
  }, [hasNextPage]);

  return (
    <div style={{ height: 400, width: '100%' }}>
      <DataGrid
        apiRef={apiRef}
        rows={rows}
        {...data}
        initialState={{ ...data.initialState, pagination: { rowCount: -1 } }}
        paginationMeta={paginationMeta}
        loading={isLoading}
        pageSizeOptions={[5, 10, 25, 50]}
        paginationModel={paginationModel}
        paginationMode="server"
        onPaginationModelChange={setPaginationModel}
      />
    </div>
  );
}

:::warning hasNextPage 변수의 값은 일부 외부 가져오기 hook이 처리하는 동안 로딩 중에 undefined가 되어 원치 않는 계산이 발생할 수 있어요. 한 가지 가능한 해결책은 paginationMeta를 메모이즈하는 것이에요:

const paginationMetaRef = React.useRef<GridPaginationMeta>();

const paginationMeta = React.useMemo(() => {
  if (
    hasNextPage !== undefined &&
    paginationMetaRef.current?.hasNextPage !== hasNextPage
  ) {
    paginationMetaRef.current = { hasNextPage };
  }
  return paginationMetaRef.current;
}, [hasNextPage]);

:::

추정된 행 수 (Estimated row count)

추정된 행 수는 "알려진 행 수"와 "알 수 없는 행 수" 사용 사례 사이를 전환하는 하이브리드 접근 방식으로 볼 수 있어요.

처음에는 estimatedRowCount가 설정되고 rowCount={-1}일 때 Data Grid는 "알 수 없는 행 수" 사용 사례처럼 동작하지만, 페이지네이션 푸터에는 estimatedRowCount 값이 표시돼요.

로드된 행 수가 estimatedRowCount를 초과하면 Data Grid는 estimatedRowCount를 무시하고 동작은 "알 수 없는 행 수" 사용 사례와 동일해져요.

hasNextPage가 false를 반환하거나 rowCount가 양수로 설정되면 Data Grid는 "알려진 행 수" 동작으로 전환해요.

다음 예제에서 실제 행 수는 1000이지만 Data Grid는 처음에 estimatedRowCount={100}으로 제공돼요. "Set Row Count" 버튼을 눌러 rowCount를 실제 행 수로 설정할 수 있어요.

import * as React from 'react';
import Button from '@mui/material/Button';
import { DataGrid, useGridApiRef } from '@mui/x-data-grid';
import type { GridPaginationMeta } from '@mui/x-data-grid';
import { createFakeServer } from '@mui/x-data-grid-generator';

const SERVER_OPTIONS = {
  useCursorPagination: false,
};

const { useQuery, ...data } = createFakeServer({ rowLength: 1000 }, SERVER_OPTIONS);

export default function ServerPaginationGridEstimated() {
  const apiRef = useGridApiRef();
  const [paginationModel, setPaginationModel] = React.useState({
    page: 0,
    pageSize: 50,
  });

  const {
    isLoading,
    rows,
    pageInfo: { hasNextPage },
  } = useQuery(paginationModel);

  const paginationMetaRef = React.useRef<GridPaginationMeta>({});
  // Memoize to avoid flickering when the `hasNextPage` is `undefined` during refetch
  const paginationMeta = React.useMemo(() => {
    if (
      hasNextPage !== undefined &&
      paginationMetaRef.current?.hasNextPage !== hasNextPage
    ) {
      paginationMetaRef.current = { hasNextPage };
    }
    return paginationMetaRef.current;
  }, [hasNextPage]);

  return (
    <div style={{ width: '100%' }}>
      <Button onClick={() => apiRef.current?.setRowCount(1000)}>
        Set Row Count
      </Button>
      <div style={{ height: 400 }}>
        <DataGrid
          apiRef={apiRef}
          rows={rows}
          {...data}
          initialState={{ ...data.initialState, pagination: { rowCount: -1 } }}
          estimatedRowCount={100}
          paginationMeta={paginationMeta}
          loading={isLoading}
          pageSizeOptions={[10, 25, 50, 100]}
          paginationModel={paginationModel}
          paginationMode="server"
          onPaginationModelChange={setPaginationModel}
        />
      </div>
    </div>
  );
}

:::warning 가져올 레코드가 실제로 남아 있지 않을 때까지 hasNextPage를 false로 설정하면 안 돼요. hasNextPage가 false가 되면 Grid는 이를 마지막 페이지로 간주하고 rowCount 값을 유한한 값으로 설정하려 하기 때문이에요.

외부 데이터 가져오기 라이브러리가 로딩 중에 값을 undefined로 설정한다면, "알 수 없는 행 수" 섹션에서처럼 paginationMeta 값을 메모이즈해 로딩 중에 변하지 않도록 할 수 있어요. :::

:::info

🌍 추정된 행 수의 지역화

Data Grid는 Material UI 라이브러리의 Table Pagination 컴포넌트를 사용하는데, 이 컴포넌트는 estimated 행 수를 지원하지 않아요. Table Pagination 컴포넌트에서 이를 기본적으로 지원할 때까지, 지역화가 작동하도록 하는 우회 방법은 관심 있는 로케일에 따라 localeText 객체에 paginationDisplayedRows 함수를 제공하는 것이에요.

Grid는 paginationDisplayedRows 함수에 estimated라는 추가 변수를 주입하며, 이를 사용해 추정된 행 수를 반영할 수 있어요. 다음 예제는 크로아티아어(hr-HR)로 페이지네이션 푸터에 추정된 행 수를 표시하는 방법을 보여줘요.

const paginationDisplayedRows = ({ from, to, count, estimated }) => {
  if (!estimated) {
    return `${from}–${to} od ${count !== -1 ? count : `više nego ${to}`}`;
  }
  const estimateLabel =
    estimated && estimated > to ? `oko ${estimated}` : `više nego ${to}`;
  return `${from}–${to} od ${count !== -1 ? count : estimateLabel}`;
};

<DataGrid {...data} localeText={{ paginationDisplayedRows }} />;

자세한 내용은 지역화 문서의 Translation keys 섹션을 참고하세요.

:::

커서 기반 페이지네이션 (Cursor-based pagination)

커서 기반 페이지네이션이 있는 서버도 처리할 수 있어요. 그렇게 하려면 가져온 각 페이지와 연관된 다음 커서(next cursor)를 계속 추적하기만 하면 돼요.

import * as React from 'react';
import {
  DataGrid,
  GridRowId,
  GridPaginationModel,
  GridPaginationMeta,
} from '@mui/x-data-grid';
import Radio from '@mui/material/Radio';
import RadioGroup from '@mui/material/RadioGroup';
import FormControlLabel from '@mui/material/FormControlLabel';
import FormControl from '@mui/material/FormControl';
import FormLabel from '@mui/material/FormLabel';
import { createFakeServer } from '@mui/x-data-grid-generator';

const PAGE_SIZE = 5;

const SERVER_OPTIONS = {
  useCursorPagination: true,
};

const { useQuery, ...data } = createFakeServer({}, SERVER_OPTIONS);

type RowCountType = 'known' | 'unknown' | 'estimated';

export default function CursorPaginationGrid() {
  const [rowCountType, setRowCountType] = React.useState<RowCountType>('known');

  const mapPageToNextCursor = React.useRef<{ [page: number]: GridRowId }>({});

  const [paginationModel, setPaginationModel] = React.useState({
    page: 0,
    pageSize: PAGE_SIZE,
  });

  const queryOptions = React.useMemo(
    () => ({
      cursor: mapPageToNextCursor.current[paginationModel.page - 1],
      pageSize: paginationModel.pageSize,
    }),
    [paginationModel],
  );
  const {
    isLoading,
    rows,
    pageInfo: { hasNextPage, nextCursor, totalRowCount },
  } = useQuery(queryOptions);

  const handlePaginationModelChange = (newPaginationModel: GridPaginationModel) => {
    // We have the cursor, we can allow the page transition.
    if (
      newPaginationModel.page === 0 ||
      mapPageToNextCursor.current[newPaginationModel.page - 1]
    ) {
      setPaginationModel(newPaginationModel);
    }
  };

  const paginationMetaRef = React.useRef<GridPaginationMeta>(undefined);

  // Memoize to avoid flickering when the `hasNextPage` is `undefined` during refetch
  const paginationMeta = React.useMemo(() => {
    if (
      hasNextPage !== undefined &&
      paginationMetaRef.current?.hasNextPage !== hasNextPage
    ) {
      paginationMetaRef.current = { hasNextPage };
    }
    return paginationMetaRef.current;
  }, [hasNextPage]);

  React.useEffect(() => {
    if (!isLoading && nextCursor) {
      // We add nextCursor when available
      mapPageToNextCursor.current[paginationModel.page] = nextCursor;
    }
  }, [paginationModel.page, isLoading, nextCursor]);

  // Some API clients return undefined while loading
  // Following lines are here to prevent `rowCountState` from being undefined during the loading
  const [rowCountState, setRowCountState] = React.useState(totalRowCount || 0);
  React.useEffect(() => {
    if (rowCountType === 'known') {
      setRowCountState((prevRowCountState) =>
        totalRowCount !== undefined ? totalRowCount : prevRowCountState,
      );
    }
    if (
      (rowCountType === 'unknown' || rowCountType === 'estimated') &&
      paginationMeta?.hasNextPage !== false
    ) {
      setRowCountState(-1);
    }
  }, [paginationMeta?.hasNextPage, rowCountType, totalRowCount]);

  const prevEstimatedRowCount = React.useRef<number | undefined>(undefined);
  const estimatedRowCount = React.useMemo(() => {
    if (rowCountType === 'estimated') {
      if (totalRowCount !== undefined) {
        if (prevEstimatedRowCount.current === undefined) {
          prevEstimatedRowCount.current = totalRowCount / 2;
        }
        return totalRowCount / 2;
      }
      return prevEstimatedRowCount.current;
    }
    return undefined;
  }, [rowCountType, totalRowCount]);

  return (
    <div style={{ width: '100%' }}>
      <FormControl>
        <FormLabel id="demo-cursor-pagination-buttons-group-label">
          Row count
        </FormLabel>
        <RadioGroup
          row
          aria-labelledby="demo-cursor-pagination-buttons-group-label"
          name="cursor-pagination-buttons-group"
          value={rowCountType}
          onChange={(event) => setRowCountType(event.target.value as RowCountType)}
        >
          <FormControlLabel value="known" control={<Radio />} label="Known" />
          <FormControlLabel value="unknown" control={<Radio />} label="Unknown" />
          <FormControlLabel
            value="estimated"
            control={<Radio />}
            label="Estimated"
          />
        </RadioGroup>
      </FormControl>
      <div style={{ height: 400 }}>
        <DataGrid
          rows={rows}
          {...data}
          pageSizeOptions={[PAGE_SIZE]}
          rowCount={rowCountState}
          onRowCountChange={(newRowCount) => setRowCountState(newRowCount)}
          estimatedRowCount={estimatedRowCount}
          paginationMeta={paginationMeta}
          paginationMode="server"
          onPaginationModelChange={handlePaginationModelChange}
          paginationModel={paginationModel}
          loading={isLoading}
        />
      </div>
    </div>
  );
}

커스텀 페이지네이션 UI (Custom pagination UI)

문서의 컴포넌트 섹션에 따라 푸터의 페이지네이션 렌더링을 커스터마이즈할 수 있어요.

apiRef

Data Grid는 페이지네이션 기능의 구현에서 내부적으로 사용되는 일련의 메서드를 apiRef 객체를 통해 노출해요. 아래 참조는 관련 함수를 설명해요. 자세한 내용은 API object를 참고하세요.

:::warning 이 API는 Data Grid의 내장 props가 특정 사용 사례에 충분하지 않을 때 최후의 수단으로만 사용해야 해요. :::

import ApiDocs from 'docs/src/modules/components/ApiDocs';
import api from 'docs/pages/x/api/data-grid/grid-pagination-api.json';

export default function PaginationApiNoSnap() {
  return <ApiDocs api={api} />;
}

선택기 (Selectors)

{{"component": "modules/components/SelectorsDocs.js", "category": "Pagination"}}

선택기와 사용 방법에 대한 자세한 내용은 전용 페이지에서 확인할 수 있어요.

API

더 알아보기 (Learn more)