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

Data Grid - 행 사용자 지정 레시피

원문 보기 위키 갱신

Data Grid - 행 사용자 지정 레시피 (Row customization recipes)

고급 행 사용자 지정 레시피.

출처: MUI X documentation

본문

한 번에 하나의 상세 패널만 펼치기 (One expanded detail panel at a time)

기본적으로 마스터-디테일 행 패널 기능은 여러 개의 상세 패널을 동시에 펼친 상태로 지원합니다.

하지만 펼쳐진 상세 패널 제어로 한 번에 하나의 상세 패널만 펼치도록 할 수 있습니다.

import * as React from 'react';
import Box from '@mui/material/Box';
import {
  DataGridPro,
  DataGridProProps,
  GridRowsProp,
  GridRowId,
  GridColDef,
} from '@mui/x-data-grid-pro';
import {
  randomCreatedDate,
  randomCurrency,
  randomEmail,
  randomPrice,
} from '@mui/x-data-grid-generator';

const getDetailPanelContent: DataGridProProps['getDetailPanelContent'] = ({
  row,
}) => <Box sx={{ p: 2 }}>{`Order #${row.id}`}</Box>;
const getDetailPanelHeight: DataGridProProps['getDetailPanelHeight'] = () => 50;

export default function DetailPanelOneExpandedRow() {
  const [detailPanelExpandedRowIds, setDetailPanelExpandedRowIds] = React.useState(
    () => new Set<GridRowId>(),
  );

  const handleDetailPanelExpandedRowIdsChange = React.useCallback<
    NonNullable<DataGridProProps['onDetailPanelExpandedRowIdsChange']>
  >((newIds) => {
    if (newIds.size > 1) {
      const newSet = new Set<GridRowId>();
      const newIdsArray = Array.from(newIds);
      newSet.add(newIdsArray[newIdsArray.length - 1]);
      setDetailPanelExpandedRowIds(newSet);
    } else {
      setDetailPanelExpandedRowIds(newIds);
    }
  }, []);

  return (
    <Box sx={{ height: 400, width: '100%' }}>
      <DataGridPro
        rows={rows}
        columns={columns}
        getDetailPanelContent={getDetailPanelContent}
        getDetailPanelHeight={getDetailPanelHeight}
        detailPanelExpandedRowIds={detailPanelExpandedRowIds}
        onDetailPanelExpandedRowIdsChange={handleDetailPanelExpandedRowIdsChange}
      />
    </Box>
  );
}

const columns: GridColDef[] = [
  { field: 'id', headerName: 'Order ID' },
  { field: 'customer', headerName: 'Customer', width: 200, rowHeader: true },
  { field: 'date', type: 'date', headerName: 'Placed at' },
  { field: 'currency', headerName: 'Currency' },
  { field: 'total', type: 'number', headerName: 'Total' },
];

const rows: GridRowsProp = [
  {
    id: 1,
    customer: 'Matheus',
    email: randomEmail(),
    date: randomCreatedDate(),
    currency: randomCurrency(),
    total: randomPrice(1, 1000),
  },
  {
    id: 2,
    customer: 'Olivier',
    email: randomEmail(),
    date: randomCreatedDate(),
    currency: randomCurrency(),
    total: randomPrice(1, 1000),
  },
  {
    id: 3,
    customer: 'Flavien',
    email: randomEmail(),
    date: randomCreatedDate(),
    currency: randomCurrency(),
    total: randomPrice(1, 1000),
  },
  {
    id: 4,
    customer: 'Danail',
    email: randomEmail(),
    date: randomCreatedDate(),
    currency: randomCurrency(),
    total: randomPrice(1, 1000),
  },
  {
    id: 5,
    customer: 'Alexandre',
    email: randomEmail(),
    date: randomCreatedDate(),
    currency: randomCurrency(),
    total: randomPrice(1, 1000),
  },
];

모든 상세 패널 펼치기/접기 (Expand or collapse all detail panels)

아래 데모는 모든 상세 패널을 한 번에 펼치거나 접는 사용자 지정 헤더 요소를 만드는 방법을 보여 줍니다.

동작 방식은 다음과 같습니다:

사용자 지정 헤더는 gridRowsLookupSelector를 사용해 상세 패널이 있는 모든 행을 찾습니다. 그리드의 상태에 접근하기 위해 useGridSelector() 훅을 사용해 열린 패널의 상태를 확인합니다. 클릭하면 Grid API의 setExpandedDetailPanels를 사용해 모든 상세 패널을 펼치거나 접습니다.

import * as React from 'react';
import Box from '@mui/material/Box';
import IconButton from '@mui/material/IconButton';
import UnfoldLessIcon from '@mui/icons-material/UnfoldLess';
import UnfoldMoreIcon from '@mui/icons-material/UnfoldMore';
import {
  DataGridPro,
  GridColDef,
  GridRowsProp,
  GridRowParams,
  useGridApiContext,
  useGridSelector,
  gridRowsLookupSelector,
  gridDetailPanelExpandedRowIdsSelector,
  gridDetailPanelExpandedRowsContentCacheSelector,
  GRID_DETAIL_PANEL_TOGGLE_COL_DEF,
  GridRowId,
} from '@mui/x-data-grid-pro';
import {
  randomCreatedDate,
  randomCurrency,
  randomEmail,
  randomPrice,
} from '@mui/x-data-grid-generator';

export default function DetailPanelExpandCollapseAll() {
  const getDetailPanelContent = React.useCallback(
    ({ row }: GridRowParams) => <Box sx={{ p: 2 }}>{`Order #${row.id}`}</Box>,
    [],
  );

  const getDetailPanelHeight = React.useCallback(() => 50, []);

  return (
    <div style={{ height: 400, width: '100%' }}>
      <DataGridPro
        rows={rows}
        columns={columns}
        getDetailPanelContent={getDetailPanelContent}
        getDetailPanelHeight={getDetailPanelHeight}
      />
    </div>
  );
}

function CustomDetailPanelHeader() {
  const apiRef = useGridApiContext();

  const expandedRowIds = useGridSelector(
    apiRef,
    gridDetailPanelExpandedRowIdsSelector,
  );
  const rowsWithDetailPanels = useGridSelector(
    apiRef,
    gridDetailPanelExpandedRowsContentCacheSelector,
  );

  const noDetailPanelsOpen = expandedRowIds.size === 0;

  const expandOrCollapseAll = () => {
    if (noDetailPanelsOpen) {
      const dataRowIdToModelLookup = gridRowsLookupSelector(apiRef);
      const allRowIdsWithDetailPanels = new Set<GridRowId>();
      for (const key in rowsWithDetailPanels) {
        if (rowsWithDetailPanels.hasOwnProperty(key)) {
          allRowIdsWithDetailPanels.add(
            apiRef.current.getRowId(dataRowIdToModelLookup[key]),
          );
        }
      }
      apiRef.current.setExpandedDetailPanels(allRowIdsWithDetailPanels);
    } else {
      apiRef.current.setExpandedDetailPanels(new Set());
    }
  };

  const Icon = noDetailPanelsOpen ? UnfoldMoreIcon : UnfoldLessIcon;

  return (
    <IconButton
      size="small"
      tabIndex={-1}
      onClick={expandOrCollapseAll}
      aria-label={noDetailPanelsOpen ? 'Expand All' : 'Collapse All'}
    >
      <Icon fontSize="inherit" />
    </IconButton>
  );
}

const columns: GridColDef[] = [
  {
    ...GRID_DETAIL_PANEL_TOGGLE_COL_DEF,
    renderHeader: () => <CustomDetailPanelHeader />,
  },
  { field: 'id', headerName: 'Order ID' },
  { field: 'customer', headerName: 'Customer', width: 200, rowHeader: true },
  { field: 'date', type: 'date', headerName: 'Placed at' },
  { field: 'currency', headerName: 'Currency' },
  { field: 'total', type: 'number', headerName: 'Total' },
];

const rows: GridRowsProp = [
  {
    id: 1,
    customer: 'Matheus',
    email: randomEmail(),
    date: randomCreatedDate(),
    currency: randomCurrency(),
    total: randomPrice(1, 1000),
  },
  {
    id: 2,
    customer: 'Olivier',
    email: randomEmail(),
    date: randomCreatedDate(),
    currency: randomCurrency(),
    total: randomPrice(1, 1000),
  },
  {
    id: 3,
    customer: 'Flavien',
    email: randomEmail(),
    date: randomCreatedDate(),
    currency: randomCurrency(),
    total: randomPrice(1, 1000),
  },
  {
    id: 4,
    customer: 'Danail',
    email: randomEmail(),
    date: randomCreatedDate(),
    currency: randomCurrency(),
    total: randomPrice(1, 1000),
  },
  {
    id: 5,
    customer: 'Alexandre',
    email: randomEmail(),
    date: randomCreatedDate(),
    currency: randomCurrency(),
    total: randomPrice(1, 1000),
  },
];

행 클릭으로 상세 패널 토글 (Toggling detail panels on row click)

아래 데모에서는 행의 아무 곳이나 클릭해 상세 패널을 토글할 수 있습니다:

import * as React from 'react';
import Box from '@mui/material/Box';
import Grid from '@mui/material/Grid';
import Typography from '@mui/material/Typography';
import Paper from '@mui/material/Paper';
import Stack from '@mui/material/Stack';
import {
  DataGridPro,
  DataGridProProps,
  GridColDef,
  GridEventListener,
  useGridApiRef,
} from '@mui/x-data-grid-pro';
import {
  randomCreatedDate,
  randomPrice,
  randomCurrency,
  randomCountry,
  randomCity,
  randomEmail,
  randomInt,
  randomAddress,
  randomCommodity,
} from '@mui/x-data-grid-generator';

function DetailPanelContent({ row: rowProp }: { row: Customer }) {
  return (
    <Stack
      sx={{ py: 2, height: '100%', boxSizing: 'border-box' }}
      direction="column"
    >
      <Paper sx={{ flex: 1, mx: 'auto', width: '90%', p: 1 }}>
        <Stack direction="column" spacing={1} sx={{ height: 1 }}>
          <Typography variant="h6">{`Order #${rowProp.id}`}</Typography>
          <Grid container>
            <Grid size={{ md: 6 }}>
              <Typography variant="body2" color="textSecondary">
                Customer information
              </Typography>
              <Typography variant="body1">{rowProp.customer}</Typography>
              <Typography variant="body1">{rowProp.email}</Typography>
            </Grid>
            <Grid size={{ md: 6 }}>
              <Typography variant="body2" align="right" color="textSecondary">
                Shipping address
              </Typography>
              <Typography variant="body1" align="right">
                {rowProp.address}
              </Typography>
              <Typography
                variant="body1"
                align="right"
              >{`${rowProp.city}, ${rowProp.country.label}`}</Typography>
            </Grid>
          </Grid>
          <DataGridPro
            density="compact"
            columns={[
              { field: 'name', headerName: 'Product', flex: 1, rowHeader: true },
              {
                field: 'quantity',
                headerName: 'Quantity',
                align: 'center',
                type: 'number',
              },
              { field: 'unitPrice', headerName: 'Unit Price', type: 'number' },
              {
                field: 'total',
                headerName: 'Total',
                type: 'number',
                valueGetter: (value, row) => row.quantity * row.unitPrice,
              },
            ]}
            rows={rowProp.products}
            sx={{ flex: 1 }}
            hideFooter
          />
        </Stack>
      </Paper>
    </Stack>
  );
}

const columns: GridColDef<(typeof rows)[number]>[] = [
  { field: 'id', headerName: 'Order ID' },
  { field: 'customer', headerName: 'Customer', width: 200 },
  { field: 'date', type: 'date', headerName: 'Placed at' },
  { field: 'currency', headerName: 'Currency' },
  {
    field: 'total',
    type: 'number',
    headerName: 'Total',
    valueGetter: (value, row) => {
      const subtotal = row.products.reduce(
        (acc: number, product: any) => product.unitPrice * product.quantity,
        0,
      );
      const taxes = subtotal * 0.05;
      return subtotal + taxes;
    },
  },
];

function generateProducts() {
  const quantity = randomInt(1, 5);
  return [...Array(quantity)].map((_, index) => ({
    id: index,
    name: randomCommodity(),
    quantity: randomInt(1, 5),
    unitPrice: randomPrice(1, 1000),
  }));
}

const rows = [
  {
    id: 1,
    customer: 'Matheus',
    email: randomEmail(),
    date: randomCreatedDate(),
    address: randomAddress(),
    country: randomCountry(),
    city: randomCity(),
    currency: randomCurrency(),
    products: generateProducts(),
  },
  {
    id: 2,
    customer: 'Olivier',
    email: randomEmail(),
    date: randomCreatedDate(),
    address: randomAddress(),
    country: randomCountry(),
    city: randomCity(),
    currency: randomCurrency(),
    products: generateProducts(),
  },
  {
    id: 3,
    customer: 'Flavien',
    email: randomEmail(),
    date: randomCreatedDate(),
    address: randomAddress(),
    country: randomCountry(),
    city: randomCity(),
    currency: randomCurrency(),
    products: generateProducts(),
  },
  {
    id: 4,
    customer: 'Danail',
    email: randomEmail(),
    date: randomCreatedDate(),
    address: randomAddress(),
    country: randomCountry(),
    city: randomCity(),
    currency: randomCurrency(),
    products: generateProducts(),
  },
  {
    id: 5,
    customer: 'Alexandre',
    email: randomEmail(),
    date: randomCreatedDate(),
    address: randomAddress(),
    country: randomCountry(),
    city: randomCity(),
    currency: randomCurrency(),
    products: generateProducts(),
  },
];

type Customer = (typeof rows)[number];

export default function DetailPanelExpandOnRowClick() {
  const getDetailPanelContent = React.useCallback<
    NonNullable<DataGridProProps['getDetailPanelContent']>
  >(({ row }) => <DetailPanelContent row={row} />, []);

  const getDetailPanelHeight = React.useCallback(() => 400, []);

  const apiRef = useGridApiRef();

  const onRowClick = React.useCallback<GridEventListener<'rowClick'>>(
    (params) => {
      apiRef.current?.toggleDetailPanel(params.id);
    },
    [apiRef],
  );

  return (
    <Box sx={{ width: '100%', height: 400 }}>
      <DataGridPro
        apiRef={apiRef}
        columns={columns}
        onRowClick={onRowClick}
        rows={rows}
        getDetailPanelHeight={getDetailPanelHeight}
        getDetailPanelContent={getDetailPanelContent}
      />
    </Box>
  );
}

자동 높이와 함께 상세 패널 지연 로딩 (Lazy loading detail panels with auto height)

아래 데모에서 상세 패널은 콘텐츠에 기반한 높이(자동 높이)를 가지며 지연 로딩됩니다. 스크롤 문제를 방지하기 위해 패널 높이는 로드된 후 캐시되고, 캐시된 높이가 getDetailPanelHeight() 콜백에서 반환됩니다.

import * as React from 'react';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import Paper from '@mui/material/Paper';
import Stack from '@mui/material/Stack';
import {
  randomEmail,
  randomInt,
  randomCommodity,
  randomPrice,
  randomTraderName,
  randomId,
} from '@mui/x-data-grid-generator';
import {
  DataGridPro,
  DataGridProProps,
  GridColDef,
  GridRowId,
  GridRowParams,
} from '@mui/x-data-grid-pro';
import { DetailPanelWrapper, useDetailPanelCache } from './detailPanelCache';

type Products = Awaited<ReturnType<typeof getProducts>>;

const DetailPanelDataCache = React.createContext(new Map<GridRowId, Products>());

async function getProducts(orderId: Customer['id']) {
  await new Promise((resolve) => {
    setTimeout(resolve, 1000);
  });

  const quantity = randomInt(30, 50);
  return [...Array(quantity)].map((_, index) => ({
    id: index,
    orderId,
    name: randomCommodity(),
    quantity: randomInt(1, 5),
    unitPrice: randomPrice(1, 1000),
  }));
}

const detailPanelColumns: GridColDef[] = [
  { field: 'name', headerName: 'Product', flex: 1, rowHeader: true },
  {
    field: 'quantity',
    headerName: 'Quantity',
    align: 'center',
    type: 'number',
  },
  { field: 'unitPrice', headerName: 'Unit Price', type: 'number' },
  {
    field: 'total',
    headerName: 'Total',
    type: 'number',
    valueGetter: (value, row) => row.quantity * row.unitPrice,
  },
];

function DetailPanelContent({
  row: rowProp,
  onLoaded,
}: {
  row: Customer;
  onLoaded?: () => void;
}) {
  const [isLoading, setLoading] = React.useState(true);
  const [products, setProducts] = React.useState<
    Awaited<ReturnType<typeof getProducts>>
  >([]);

  const detailPanelDataCache = React.useContext(DetailPanelDataCache) as Map<
    GridRowId,
    Products
  >;

  React.useEffect(() => {
    let isMounted = true;
    (async () => {
      if (!detailPanelDataCache.has(rowProp.id)) {
        console.log('fetching detail panel content for row', rowProp.id);
        const response = await getProducts(rowProp.id);
        // Store the data in cache so that when detail panel unmounts due to virtualization, the data is not lost
        detailPanelDataCache.set(rowProp.id, response);
      }

      const result = detailPanelDataCache.get(rowProp.id)!;

      if (!isMounted) {
        return;
      }

      setProducts(result);
      setLoading(false);
      onLoaded?.();
    })();

    return () => {
      isMounted = false;
    };
  }, [rowProp.id, detailPanelDataCache, onLoaded]);

  return (
    <Stack
      sx={{ py: 2, height: '100%', boxSizing: 'border-box' }}
      direction="column"
    >
      <Paper sx={{ flex: 1, mx: 'auto', width: '90%', p: 1 }}>
        <Stack direction="column" spacing={1} sx={{ height: 1 }}>
          <Typography variant="h6">{`Order #${rowProp.id}`}</Typography>
          <DataGridPro
            density="compact"
            loading={isLoading}
            columns={detailPanelColumns}
            rows={products}
            sx={{ flex: 1 }}
            hideFooter
          />
        </Stack>
      </Paper>
    </Stack>
  );
}

const columns: GridColDef[] = [
  { field: 'customer', headerName: 'Customer', width: 200 },
  { field: 'email', headerName: 'Email', width: 200 },
];

function getRow() {
  return {
    id: randomId(),
    customer: randomTraderName(),
    email: randomEmail(),
  };
}

const rows: ReturnType<typeof getRow>[] = [];
for (let i = 0; i < 30; i += 1) {
  rows.push(getRow());
}

type Customer = (typeof rows)[number];

export default function LazyLoadingAutoHeightDetailPanel() {
  const {
    detailPanelDataCache,
    detailPanelHeights,
    handleDetailPanelHeightChange,
    handleDetailPanelExpansionChange,
  } = useDetailPanelCache<Products>();

  const getDetailPanelHeight = React.useCallback(
    (params: { row: Customer }) => {
      const cachedHeight = detailPanelHeights.get(params.row.id);
      return cachedHeight ?? ('auto' as const);
    },
    [detailPanelHeights],
  );

  const getDetailPanelContent: DataGridProProps['getDetailPanelContent'] =
    React.useCallback(
      (params: GridRowParams<Customer>) => (
        <DetailPanelWrapper
          rowId={params.row.id}
          onHeightChange={handleDetailPanelHeightChange}
        >
          <DetailPanelContent row={params.row} />
        </DetailPanelWrapper>
      ),
      [handleDetailPanelHeightChange],
    );

  return (
    <Box sx={{ width: '100%', height: 400 }}>
      <DetailPanelDataCache.Provider value={detailPanelDataCache}>
        <DataGridPro
          columns={columns}
          rows={rows}
          getDetailPanelHeight={getDetailPanelHeight}
          getDetailPanelContent={getDetailPanelContent}
          onDetailPanelExpandedRowIdsChange={handleDetailPanelExpansionChange}
        />
      </DetailPanelDataCache.Provider>
    </Box>
  );
}

Data Grid 내부 로딩 상태 접근 (Access Data Grid internal loading state)

아래 데모는 useGridSelector() 훅을 gridRowsLoadingSelector()와 함께 사용해 Data Grid가 로딩 상태일 때 툴바의 버튼을 비활성화하는 방법을 보여 줍니다.

import Button from '@mui/material/Button';
import {
  DataGrid,
  Toolbar,
  useGridApiContext,
  gridRowsLoadingSelector,
  useGridSelector,
} from '@mui/x-data-grid';

function CustomToolbar() {
  const apiRef = useGridApiContext();
  const isLoading = useGridSelector(apiRef, gridRowsLoadingSelector);
  return (
    <Toolbar>
      <Button
        variant="outlined"
        loading={isLoading}
        onClick={() => apiRef.current?.setLoading(true)}
      >
        Set Loading
      </Button>
      {isLoading && (
        <Button onClick={() => apiRef.current?.setLoading(false)}>Cancel</Button>
      )}
    </Toolbar>
  );
}

const rows = [
  { id: 1, name: 'React' },
  { id: 2, name: 'MUI' },
];

const columns = [{ field: 'name', rowHeader: true }];

export default function AccessingLoadingState() {
  return (
    <div style={{ height: 300, width: '100%' }}>
      <DataGrid
        columns={columns}
        rows={rows}
        slots={{ toolbar: CustomToolbar }}
        showToolbar
      />
    </div>
  );
}

:::info useGridSelector()는 React Context를 기반으로 하므로, 컴포넌트가 React 트리에서 Data Grid의 자식이어야 내부 상태에 접근할 수 있습니다.

React 포털을 사용하면 Data Grid DOM 트리 밖에서 컴포넌트를 렌더링하면서도 같은 결과를 얻을 수 있습니다. :::

재정렬 중 페이지 간 행 드래그 (Drag rows between pages while reordering)

기본적으로 행 재정렬은 드래그된 행과 드롭 대상이 같은 페이지에 렌더링되어 있어야 합니다. 사용자 지정 페이징 컴포넌트를 사용해 행이 드래그되는 동안 페이지를 전환할 수 있습니다.

다음 데모는 사용자 지정 페이징 컴포넌트에서 rowDragStart와 rowDragEnd 이벤트를 수신합니다. 행이 이전 또는 다음 페이지 버튼 위로 드래그되면 컴포넌트가 dragOver 단계에서 페이지를 변경합니다. 페이지가 변경된 후 새 페이지의 원하는 위치에 드롭합니다.

import * as React from 'react';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import KeyboardArrowLeftIcon from '@mui/icons-material/KeyboardArrowLeft';
import KeyboardArrowRightIcon from '@mui/icons-material/KeyboardArrowRight';
import { alpha } from '@mui/material/styles';
import {
  DataGridPro,
  GridRowModel,
  GridRowOrderChangeParams,
  gridPageSelector,
  gridPageCountSelector,
  useGridApiContext,
  useGridEvent,
  useGridSelector,
} from '@mui/x-data-grid-pro';
import { useDemoData } from '@mui/x-data-grid-generator';

const PAGE_TURN_DELAY = 500;

type PageTurnDirection = 'previous' | 'next';

function updateRowPosition(
  initialIndex: number,
  newIndex: number,
  rows: GridRowModel[],
) {
  const rowsClone = [...rows];
  const row = rowsClone.splice(initialIndex, 1)[0];
  rowsClone.splice(newIndex, 0, row);
  return rowsClone;
}

function Pagination() {
  const apiRef = useGridApiContext();
  const page = useGridSelector(apiRef, gridPageSelector);
  const pageCount = useGridSelector(apiRef, gridPageCountSelector);
  const [isDraggingRow, setIsDraggingRow] = React.useState(false);
  const [pageTurnDirection, setPageTurnDirection] =
    React.useState<PageTurnDirection | null>(null);
  const pageTurnTimeout = React.useRef<ReturnType<typeof setTimeout> | null>(null);

  const clearPageTurnTimeout = React.useCallback(() => {
    if (pageTurnTimeout.current != null) {
      clearTimeout(pageTurnTimeout.current);
      pageTurnTimeout.current = null;
    }
    setPageTurnDirection(null);
  }, []);

  useGridEvent(apiRef, 'rowDragStart', () => {
    setIsDraggingRow(true);
  });

  useGridEvent(apiRef, 'rowDragEnd', () => {
    setIsDraggingRow(false);
    clearPageTurnTimeout();
  });

  React.useEffect(() => clearPageTurnTimeout, [clearPageTurnTimeout]);

  const handleDragOver = React.useCallback(
    (
      event: React.DragEvent<HTMLButtonElement>,
      targetPage: number,
      direction: PageTurnDirection,
    ) => {
      if (!isDraggingRow) {
        return;
      }

      event.preventDefault();
      event.dataTransfer.dropEffect = 'copy';
      setPageTurnDirection(direction);

      if (pageTurnTimeout.current != null) {
        return;
      }

      pageTurnTimeout.current = setTimeout(() => {
        apiRef.current.setPage(targetPage);
        pageTurnTimeout.current = null;
        setPageTurnDirection(null);
      }, PAGE_TURN_DELAY);
    },
    [apiRef, isDraggingRow],
  );

  const previousPage = page - 1;
  const nextPage = page + 1;
  const isPreviousDisabled = page === 0;
  const isNextDisabled = page >= pageCount - 1;

  const renderPageButton = ({
    direction,
    disabled,
    icon,
    label,
    targetPage,
  }: {
    direction: PageTurnDirection;
    disabled: boolean;
    icon: React.ReactNode;
    label: string;
    targetPage: number;
  }) => {
    const isDropTarget = pageTurnDirection === direction;

    return (
      <Button
        disabled={disabled}
        onClick={() => apiRef.current.setPage(targetPage)}
        onDragLeave={clearPageTurnTimeout}
        onDragOver={(event) => handleDragOver(event, targetPage, direction)}
        startIcon={direction === 'previous' ? icon : undefined}
        endIcon={direction === 'next' ? icon : undefined}
        sx={(theme) => ({
          '@keyframes pageTurnPulse': {
            '0%': {
              boxShadow: `0 0 0 0 ${alpha(theme.palette.primary.main, 0.35)}`,
            },
            '100%': {
              boxShadow: `0 0 0 10px ${alpha(theme.palette.primary.main, 0)}`,
            },
          },
          bgcolor: isDropTarget
            ? alpha(theme.palette.primary.main, 0.12)
            : alpha(theme.palette.primary.main, 0.04),
          border: '1px solid',
          borderColor: isDropTarget
            ? theme.palette.primary.main
            : alpha(theme.palette.primary.main, 0.24),
          borderRadius: 999,
          color: 'primary.main',
          fontWeight: 700,
          minWidth: 116,
          px: 1.75,
          py: 0.75,
          position: 'relative',
          textTransform: 'none',
          transform: isDropTarget ? 'translateY(-1px) scale(1.03)' : 'none',
          transition: theme.transitions.create(
            ['background-color', 'border-color', 'box-shadow', 'transform'],
            {
              duration: theme.transitions.duration.shortest,
            },
          ),
          '&::after': {
            border: '1px dashed',
            borderColor: isDropTarget ? 'primary.main' : 'transparent',
            borderRadius: 999,
            content: '""',
            inset: -5,
            pointerEvents: 'none',
            position: 'absolute',
          },
          ...(isDropTarget && {
            animation: 'pageTurnPulse 700ms ease-out infinite',
          }),
        })}
      >
        {label}
      </Button>
    );
  };

  return (
    <Box
      sx={{
        alignItems: 'center',
        display: 'flex',
        flexShrink: 0,
        gap: 1,
        justifyContent: 'flex-end',
        minWidth: 360,
        p: 0.75,
      }}
    >
      {renderPageButton({
        direction: 'previous',
        disabled: isPreviousDisabled,
        icon: <KeyboardArrowLeftIcon fontSize="small" />,
        label: 'Previous',
        targetPage: previousPage,
      })}
      <Box
        sx={(theme) => ({
          alignItems: 'center',
          bgcolor: isDraggingRow
            ? alpha(theme.palette.primary.main, 0.08)
            : 'transparent',
          borderRadius: 999,
          color: isDraggingRow ? 'primary.main' : 'text.secondary',
          display: 'flex',
          fontWeight: isDraggingRow ? 700 : 500,
          minHeight: 34,
          px: 1.5,
          typography: 'body2',
        })}
      >
        {`Page ${page + 1} of ${pageCount}`}
      </Box>
      {renderPageButton({
        direction: 'next',
        disabled: isNextDisabled,
        icon: <KeyboardArrowRightIcon fontSize="small" />,
        label: 'Next',
        targetPage: nextPage,
      })}
    </Box>
  );
}

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

  const [rows, setRows] = React.useState(data.rows);

  React.useEffect(() => {
    setRows(data.rows);
  }, [data.rows]);

  const handleRowOrderChange = React.useCallback(
    (params: GridRowOrderChangeParams) => {
      setRows((prevRows) =>
        updateRowPosition(params.oldIndex, params.targetIndex, prevRows),
      );
    },
    [],
  );

  return (
    <Box sx={{ height: 400, width: '100%' }}>
      <DataGridPro
        {...data}
        loading={loading}
        rows={rows}
        pagination
        rowReordering
        onRowOrderChange={handleRowOrderChange}
        initialState={{
          ...data.initialState,
          pagination: { paginationModel: { pageSize: 5 } },
        }}
        pageSizeOptions={[5]}
        slots={{
          pagination: Pagination,
        }}
      />
    </Box>
  );
}

더 알아보기 (Learn more)