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

Data Grid - 행 고정

원문 보기 위키 갱신

Data Grid - 행 고정 (Row pinning)

데이터 그리드에서 행을 항상 표시되도록 고정(pinning)을 구현해봐요.

출처: MUI X documentation

본문

고정된 행(스티키(sticky), 프리즈(frozen), 잠금(locked)이라고도 함)은 Data Grid를 세로로 스크롤할 때 항상 표시돼요. Data Grid Pro에서는 행을 그리드의 위(top) 또는 아래(bottom)에 고정할 수 있어요.

행 고정 구현하기 (Implementing row pinning)

아래처럼 pinnedRows prop을 사용해 Data Grid의 top 또는 bottom에 고정할 행을 정의해요:

const pinnedRows: GridPinnedRowsProp = {
  top: [{ id: 0, brand: 'Nike' }],
  bottom: [
    { id: 1, brand: 'Adidas' },
    { id: 2, brand: 'Puma' },
  ],
};

<DataGridPro pinnedRows={pinnedRows} />;

고정 행 데이터 형식 (Pinned row data formatting)

고정 행의 데이터 형식은 rows prop과 동일해요 (데이터 공급 참고).

고정 행 데이터는 행 식별자 요구사항도 충족해야 해요.

import { DataGridPro, GridPinnedRowsProp, GridColDef } from '@mui/x-data-grid-pro';
import {
  randomCity,
  randomEmail,
  randomId,
  randomInt,
  randomTraderName,
  randomUserName,
} from '@mui/x-data-grid-generator';

const columns: GridColDef[] = [
  { field: 'name', headerName: 'Name', width: 150, rowHeader: true },
  { field: 'city', headerName: 'City', width: 150 },
  { field: 'username', headerName: 'Username' },
  { field: 'email', headerName: 'Email', width: 200 },
  { field: 'age', type: 'number', headerName: 'Age' },
];

const rows: object[] = [];

function getRow() {
  return {
    id: randomId(),
    name: randomTraderName(),
    city: randomCity(),
    username: randomUserName(),
    email: randomEmail(),
    age: randomInt(10, 80),
  };
}

for (let i = 0; i < 10; i += 1) {
  rows.push(getRow());
}

const pinnedRows: GridPinnedRowsProp = {
  top: [getRow(), getRow()],
  bottom: [getRow()],
};

export default function RowPinning() {
  return (
    <div style={{ height: 500, width: '100%' }}>
      <DataGridPro columns={columns} rows={rows} pinnedRows={pinnedRows} />
    </div>
  );
}

:::warning rows prop과 마찬가지로 pinnedRows도 두 렌더링 사이에 같은 참조를 유지해야 해요. 그렇지 않으면 Data Grid가 정렬과 필터링 같은 무거운 작업을 다시 적용해요. :::

고정 행 제어하기 (Controlling pinned rows)

pinnedRows를 동적으로 변경해 어떤 행이 고정될지 제어할 수 있어요.

아래 데모는 actions 열 유형을 사용해 사용자가 행을 그리드의 위나 아래에 고정할 수 있는 버튼을 제공해요.

import * as React from 'react';
import {
  DataGridPro,
  GridRowModel,
  GridActionsCellItem,
  GridColDef,
  GridRowId,
  GridActionsCell,
  GridRenderCellParams,
} from '@mui/x-data-grid-pro';
import ArrowUpIcon from '@mui/icons-material/ArrowUpward';
import ArrowDownIcon from '@mui/icons-material/ArrowDownward';
import Tooltip from '@mui/material/Tooltip';
import {
  randomId,
  randomTraderName,
  randomCity,
  randomUserName,
  randomEmail,
} from '@mui/x-data-grid-generator';

const data: GridRowModel[] = [];

function getRow() {
  return {
    id: randomId(),
    name: randomTraderName(),
    city: randomCity(),
    username: randomUserName(),
    email: randomEmail(),
  };
}

for (let i = 0; i < 20; i += 1) {
  data.push(getRow());
}

interface PinnedRowsIds {
  top: GridRowId[];
  bottom: GridRowId[];
}

interface PinningContextValue {
  pinnedRowsIds: PinnedRowsIds;
  pinToBottom: (id: GridRowId) => void;
  pinToTop: (id: GridRowId) => void;
  unpin: (id: GridRowId) => void;
}

const PinningContext = React.createContext<PinningContextValue>({
  pinnedRowsIds: { top: [], bottom: [] },
  pinToBottom: () => {},
  pinToTop: () => {},
  unpin: () => {},
});

function ActionsCell(props: GridRenderCellParams) {
  const { pinnedRowsIds, pinToBottom, pinToTop, unpin } =
    React.useContext(PinningContext);
  const isPinnedTop = pinnedRowsIds.top.includes(props.id);
  const isPinnedBottom = pinnedRowsIds.bottom.includes(props.id);

  if (isPinnedTop || isPinnedBottom) {
    return (
      <GridActionsCell {...props}>
        <GridActionsCellItem
          label="Unpin"
          icon={
            <Tooltip title="Unpin">
              {isPinnedTop ? <ArrowDownIcon /> : <ArrowUpIcon />}
            </Tooltip>
          }
          onClick={() => unpin(props.id)}
        />
      </GridActionsCell>
    );
  }

  return (
    <GridActionsCell {...props}>
      <GridActionsCellItem
        icon={
          <Tooltip title="Pin at the top">
            <ArrowUpIcon />
          </Tooltip>
        }
        label="Pin at the top"
        onClick={() => pinToTop(props.id)}
      />
      <GridActionsCellItem
        icon={
          <Tooltip title="Pin at the bottom">
            <ArrowDownIcon />
          </Tooltip>
        }
        label="Pin at the bottom"
        onClick={() => pinToBottom(props.id)}
      />
    </GridActionsCell>
  );
}

const columns: GridColDef<(typeof data)[number]>[] = [
  {
    field: 'actions',
    type: 'actions',
    width: 100,
    renderCell: (params) => <ActionsCell {...params} />,
  },
  { field: 'name', headerName: 'Name', width: 150, rowHeader: true },
  { field: 'city', headerName: 'City', width: 150 },
  { field: 'username', headerName: 'Username' },
  { field: 'email', headerName: 'Email', width: 200 },
];

export default function RowPinningWithActions() {
  const [pinnedRowsIds, setPinnedRowsIds] = React.useState<PinnedRowsIds>({
    top: [],
    bottom: [],
  });

  const { rows, pinnedRows } = React.useMemo(() => {
    const rowsData: GridRowModel[] = [];
    const pinnedRowsData: { top: GridRowModel[]; bottom: GridRowModel[] } = {
      top: [],
      bottom: [],
    };

    data.forEach((row) => {
      if (pinnedRowsIds.top.includes(row.id)) {
        pinnedRowsData.top.push(row);
      } else if (pinnedRowsIds.bottom.includes(row.id)) {
        pinnedRowsData.bottom.push(row);
      } else {
        rowsData.push(row);
      }
    });

    return {
      rows: rowsData,
      pinnedRows: pinnedRowsData,
    };
  }, [pinnedRowsIds]);

  const pinToTop = React.useCallback((id: GridRowId) => {
    setPinnedRowsIds((prevPinnedRowsIds) => ({
      ...prevPinnedRowsIds,
      top: [...prevPinnedRowsIds.top, id],
    }));
  }, []);

  const pinToBottom = React.useCallback((id: GridRowId) => {
    setPinnedRowsIds((prevPinnedRowsIds) => ({
      ...prevPinnedRowsIds,
      bottom: [...prevPinnedRowsIds.bottom, id],
    }));
  }, []);

  const unpin = React.useCallback((id: GridRowId) => {
    setPinnedRowsIds((prevPinnedRowsIds) => ({
      top: prevPinnedRowsIds.top.filter((rowId) => rowId !== id),
      bottom: prevPinnedRowsIds.bottom.filter((rowId) => rowId !== id),
    }));
  }, []);

  const pinningContextValue = React.useMemo<PinningContextValue>(
    () => ({
      pinnedRowsIds,
      pinToTop,
      pinToBottom,
      unpin,
    }),
    [pinnedRowsIds, pinToTop, pinToBottom, unpin],
  );

  return (
    <div style={{ height: 500, width: '100%' }}>
      <PinningContext.Provider value={pinningContextValue}>
        <DataGridPro columns={columns} pinnedRows={pinnedRows} rows={rows} />
      </PinningContext.Provider>
    </div>
  );
}

고정 행 모양 (Pinned rows appearance)

기본적으로 고정 행 섹션은 스크롤이 있을 때 나타나는 테두리와 그림자로 비고정 행과 구분돼요. pinnedRowsSectionSeparator prop을 'border' 또는 'border-and-shadow'로 설정해 모양을 바꿀 수 있어요.

import * as React from 'react';
import FormControl from '@mui/material/FormControl';
import RadioGroup from '@mui/material/RadioGroup';
import FormControlLabel from '@mui/material/FormControlLabel';
import Radio from '@mui/material/Radio';
import {
  DataGridPro,
  type GridPinnedRowsProp,
  type GridColDef,
  type DataGridProProps,
} from '@mui/x-data-grid-pro';
import {
  randomCity,
  randomEmail,
  randomId,
  randomInt,
  randomTraderName,
  randomUserName,
} from '@mui/x-data-grid-generator';

type SectionSeparator = NonNullable<DataGridProProps['pinnedRowsSectionSeparator']>;

export default function RowPinningSectionSeparator() {
  const [separator, setSeparator] =
    React.useState<SectionSeparator>('border-and-shadow');

  return (
    <div style={{ width: '100%' }}>
      <FormControl component="fieldset">
        <RadioGroup
          row
          value={separator}
          onChange={(event) => setSeparator(event.target.value as SectionSeparator)}
          name="pinned-columns-section-separator"
        >
          <FormControlLabel
            value="border-and-shadow"
            control={<Radio />}
            label={<code>&quot;border-and-shadow&quot;</code>}
          />
          <FormControlLabel
            value="border"
            control={<Radio />}
            label={<code>&quot;border&quot;</code>}
          />
        </RadioGroup>
      </FormControl>
      <div style={{ height: 500 }}>
        <DataGridPro
          columns={columns}
          rows={rows}
          pinnedRows={pinnedRows}
          pinnedRowsSectionSeparator={separator}
        />
      </div>
    </div>
  );
}

const columns: GridColDef[] = [
  { field: 'name', headerName: 'Name', width: 150, rowHeader: true },
  { field: 'city', headerName: 'City', width: 150 },
  { field: 'username', headerName: 'Username' },
  { field: 'email', headerName: 'Email', width: 200 },
  { field: 'age', type: 'number', headerName: 'Age' },
];

const rows: object[] = [];

function getRow() {
  return {
    id: randomId(),
    name: randomTraderName(),
    city: randomCity(),
    username: randomUserName(),
    email: randomEmail(),
    age: randomInt(10, 80),
  };
}

for (let i = 0; i < 10; i += 1) {
  rows.push(getRow());
}

const pinnedRows: GridPinnedRowsProp = {
  top: [getRow(), getRow()],
  bottom: [getRow()],
};

다른 기능과 함께 사용하기 (Usage with other features)

고정 행은 정렬, 필터링, 페이징에 영향을 받지 않아요. 이 기능들이 어떻게 적용되든 상관없이 고정된 상태를 유지해요.

import * as React from 'react';
import { DataGridPro } from '@mui/x-data-grid-pro';
import { useDemoData } from '@mui/x-data-grid-generator';

export default function RowPinningWithPagination() {
  const { data, loading } = useDemoData({
    dataSet: 'Commodity',
    rowLength: 100,
    maxColumns: 20,
    editable: true,
  });

  const rowsData = React.useMemo(() => {
    if (!data.rows || data.rows.length === 0) {
      return { rows: data.rows };
    }
    const [firstRow, secondRow, thirdRow, ...rows] = data.rows;
    return {
      rows,
      pinnedRows: {
        top: [firstRow],
        bottom: [secondRow, thirdRow],
      },
    };
  }, [data.rows]);

  return (
    <div style={{ height: 500, width: '100%' }}>
      <DataGridPro
        {...data}
        loading={loading}
        rows={rowsData.rows}
        pinnedRows={rowsData.pinnedRows}
        initialState={{
          ...data.initialState,
          pagination: {
            ...data.initialState?.pagination,
            paginationModel: { pageSize: 25 },
          },
        }}
        pagination
        pageSizeOptions={[5, 10, 25, 50, 100]}
      />
    </div>
  );
}

고정 행은 다음 기능을 지원하지 않아요:

  • 선택(selection)
  • 행 그룹화(row grouping)
  • 트리 데이터(tree data)
  • 행 재정렬(row reordering)
  • 마스터-디테일 행 패널(master-detail row panels)

그리드에 고정 행이 있더라도, 고정되지 않은 행에는 이 기능들을 계속 사용할 수 있어요.

API

더 알아보기 (Learn more)