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

Data Grid - 컬럼 커스터마이징 레시피

원문 보기 위키 갱신

Data Grid - 컬럼 커스터마이징 레시피 (Column customization recipes)

고급 컬럼 커스터마이징 레시피예요. 컬럼 폭·순서를 유지하거나, 긴 텍스트 팝업을 꾸미거나, 다중 선택 칩을 커스터마이징하는 실제 사례들을 다뤄요.

출처: MUI X documentation

본문

컬럼 폭과 순서 유지하기

columns prop 참조가 업데이트되면 컬럼 폭과 순서는 colDef.width와 colDef 객체의 순서로 리셋되고, 업데이트된 내용은 손실돼요. 이는 Data Grid가 columns prop의 업데이트를 새로운 컬럼 집합으로 간주하고 이전 상태를 버리기 때문이에요.

columns prop이 업데이트될 때 컬럼 폭과 순서를 유지하려면, 컬럼 상태를 사용자 영역(userland)에 영속시키는 것을 고려하세요.

import * as React from 'react';
import {
  DataGridPro,
  useGridApiRef,
  GridColDef,
  GridColumnResizeParams,
  gridColumnFieldsSelector,
  GridApiPro,
} from '@mui/x-data-grid-pro';
import Button from '@mui/material/Button';

const rows = [
  {
    id: 1,
    username: '@MUI',
    age: 20,
  },
];

export default function ColumnSizingPersistWidthOrder() {
  const apiRef = useGridApiRef();
  const [index, setIndex] = React.useState(0);
  const inputColumns = React.useMemo(
    () => [
      { field: 'id' },
      { field: 'username', width: 200, key: index, rowHeader: true },
      { field: 'age', disableReorder: true },
    ],
    [index],
  );

  const columnsState = useColumnsState(apiRef, inputColumns);

  return (
    <div style={{ width: '100%' }}>
      <Button onClick={() => setIndex((prev) => prev + 1)}>
        Update columns reference
      </Button>
      <div style={{ height: 250 }}>
        <DataGridPro
          apiRef={apiRef}
          columns={columnsState.columns}
          onColumnWidthChange={columnsState.onColumnWidthChange}
          onColumnOrderChange={columnsState.onColumnOrderChange}
          rows={rows}
        />
      </div>
    </div>
  );
}

const useColumnsState = (
  apiRef: React.RefObject<GridApiPro | null>,
  columns: GridColDef[],
) => {
  const [widths, setWidths] = React.useState<Record<GridColDef['field'], number>>(
    {},
  );
  const [orderedFields, setOrderedFields] = React.useState<GridColDef['field'][]>(
    () => columns.map((column) => column.field),
  );

  const onColumnWidthChange = React.useCallback(
    ({ colDef, width }: GridColumnResizeParams) => {
      setWidths((prev) => ({ ...prev, [colDef.field]: width }));
    },
    [setWidths],
  );

  const onColumnOrderChange = React.useCallback(() => {
    setOrderedFields(gridColumnFieldsSelector(apiRef));
  }, [apiRef, setOrderedFields]);

  const computedColumns = React.useMemo(
    () =>
      orderedFields.reduce<GridColDef[]>((acc, field) => {
        const column = columns.find((col) => col.field === field);
        if (!column) {
          return acc;
        }
        if (widths[field]) {
          acc.push({
            ...column,
            width: widths[field],
          });
          return acc;
        }
        acc.push(column);
        return acc;
      }, []),
    [columns, widths, orderedFields],
  );

  return { columns: computedColumns, onColumnWidthChange, onColumnOrderChange };
};

:::warning 컬럼 정렬(Column ordering)은 Pro 기능이에요. 사용하려면 Pro 또는 Premium plan에 있어야 해요. :::

피벗과 함께 사용하기

피벗은 피벗 모델과 행 데이터에 기반해 컬럼을 동적으로 생성해요.

columns 참조가 변경된 후 피벗된 그리드의 컬럼 폭을 유지하려면, groupingColDef와 pivotingColDef props를 사용해 자동 생성된 컬럼에 폭 업데이트를 적용하세요.

아래 데모는 앞선 예시의 useColumnsState() 수정 버전과 그룹핑·피벗 컬럼용 콜백을 함께 사용해요.

import * as React from 'react';
import {
  DataGridPremium,
  useGridApiRef,
  GridColDef,
  GridColumnResizeParams,
  GRID_ROW_GROUPING_SINGLE_GROUPING_FIELD,
} from '@mui/x-data-grid-premium';
import Button from '@mui/material/Button';

const rows = [
  {
    id: 1,
    product: 'Apples',
    region: 'North',
    quarter: 'Q1',
    sales: 1000,
    profit: 100,
    size: 'L',
  },
  {
    id: 2,
    product: 'Apples',
    region: 'South',
    quarter: 'Q1',
    sales: 1200,
    profit: 120,
    size: 'M',
  },
  {
    id: 3,
    product: 'Oranges',
    region: 'North',
    quarter: 'Q1',
    sales: 800,
    profit: 80,
    size: 'M',
  },
  {
    id: 4,
    product: 'Oranges',
    region: 'South',
    quarter: 'Q1',
    sales: 900,
    profit: 90,
    size: 'S',
  },
  {
    id: 5,
    product: 'Apples',
    region: 'North',
    quarter: 'Q2',
    sales: 1100,
    profit: 110,
    size: 'L',
  },
  {
    id: 6,
    product: 'Apples',
    region: 'South',
    quarter: 'Q2',
    sales: 1300,
    profit: 130,
    size: 'L',
  },
  {
    id: 7,
    product: 'Oranges',
    region: 'North',
    quarter: 'Q2',
    sales: 850,
    profit: 85,
    size: 'M',
  },
  {
    id: 8,
    product: 'Oranges',
    region: 'South',
    quarter: 'Q2',
    sales: 950,
    profit: 95,
    size: 'S',
  },
];

const pivotModel = {
  rows: [{ field: 'product' }, { field: 'size' }],
  columns: [{ field: 'region' }, { field: 'quarter' }],
  values: [
    { field: 'sales', aggFunc: 'sum' },
    { field: 'profit', aggFunc: 'avg' },
  ],
};

export default function ColumnSizingPersistWidthPivoting() {
  const apiRef = useGridApiRef();
  const [index, setIndex] = React.useState(0);
  const inputColumns: GridColDef[] = React.useMemo(
    () => [
      { field: 'product', headerName: 'Product', key: index, rowHeader: true },
      { field: 'region', headerName: 'Region' },
      { field: 'quarter', headerName: 'Quarter' },
      {
        field: 'sales',
        headerName: 'Sales',
        type: 'number',
      },
      {
        field: 'profit',
        headerName: 'Profit',
        type: 'number',
        valueFormatter: (value: number) => {
          if (!value) {
            return '';
          }
          return `${value}%`;
        },
      },
      {
        field: 'size',
        headerName: 'Size',
      },
    ],
    [index],
  );

  const columnsState = useColumnsState(inputColumns);

  const pivotingColDef = React.useCallback(
    (field: GridColDef['field'], group: string[]) => {
      const pivotingField = [...group, field].join('>->');
      const fieldWidth = columnsState.getColumnWidth(pivotingField);
      return fieldWidth ? { width: fieldWidth } : {};
    },
    [columnsState],
  );

  const groupingColDef = React.useCallback(() => {
    const column = apiRef.current?.getColumn(
      GRID_ROW_GROUPING_SINGLE_GROUPING_FIELD,
    );
    return column?.width ? { width: column.width } : {};
  }, [apiRef]);

  return (
    <div style={{ width: '100%' }}>
      <Button onClick={() => setIndex((prev) => prev + 1)}>
        Update columns reference
      </Button>
      <div style={{ height: 450 }}>
        <DataGridPremium
          apiRef={apiRef}
          columns={columnsState.columns}
          onColumnWidthChange={columnsState.onColumnWidthChange}
          rows={rows}
          initialState={{
            pivoting: {
              enabled: true,
              model: pivotModel,
            },
          }}
          pivotingColDef={pivotingColDef}
          groupingColDef={groupingColDef}
        />
      </div>
    </div>
  );
}

const useColumnsState = (columns: GridColDef[]) => {
  const [widths, setWidths] = React.useState<Record<GridColDef['field'], number>>(
    {},
  );

  const onColumnWidthChange = React.useCallback(
    ({ colDef, width }: GridColumnResizeParams) => {
      setWidths((prev) => ({ ...prev, [colDef.field]: width }));
    },
    [setWidths],
  );

  const getColumnWidth = React.useCallback(
    (field: string): number | undefined => widths[field],
    [widths],
  );

  const computedColumns = React.useMemo(
    () =>
      columns.reduce<GridColDef[]>((acc, column) => {
        if (widths[column.field]) {
          acc.push({
            ...column,
            width: widths[column.field],
          });
          return acc;
        }
        acc.push(column);
        return acc;
      }, []),
    [columns, widths],
  );

  return {
    columns: computedColumns,
    getColumnWidth,
    onColumnWidthChange,
  };
};

커스텀 긴 텍스트 팝업 콘텐츠

longText 컬럼 타입의 기본 렌더링 셀은 확장 버튼을 클릭했을 때 전체 텍스트 콘텐츠가 있는 팝업을 보여주기 위해 GridLongTextCell 컴포넌트를 사용해요. 팝업 콘텐츠를 커스터마이징하려면 GridLongTextCell 컴포넌트의 renderContent prop을 사용하세요.

아래 예시는 두 가지 커스터마이징을 보여줘요:

  • 문자 수(Character count): 텍스트 아래에 문자 수를 보여줘요
  • 마크다운 미리보기(Markdown preview): 마크다운 콘텐츠를 포맷된 HTML로 렌더링해요
import * as React from 'react';
import Box from '@mui/material/Box';
import { DataGrid, GridColDef, GridLongTextCell } from '@mui/x-data-grid';
import { styled } from '@mui/material/styles';
import Markdown from 'markdown-to-jsx';

const rows = [
  {
    id: 1,
    title: 'Introduction to React',
    notes:
      'React is a JavaScript library for building user interfaces. It uses a component-based architecture and virtual DOM for efficient updates.',
    markdown:
      '# Getting Started\n\nTo create a new React app:\n\n```bash\nnpx create-react-app my-app\n```\n\n**Key concepts:**\n- Components\n- Props\n- State',
  },
  {
    id: 2,
    title: 'TypeScript Basics',
    notes:
      'TypeScript adds static type definitions to JavaScript. It helps catch errors early and improves code maintainability in large codebases.',
    markdown:
      '## Type Annotations\n\nBasic types:\n\n```typescript\nlet name: string = "John";\nlet age: number = 30;\nlet active: boolean = true;\n```\n\n*TypeScript compiles to plain JavaScript.*',
  },
  {
    id: 3,
    title: 'MUI Data Grid',
    notes:
      'The MUI X Data Grid is a powerful component for displaying and editing tabular data. It supports sorting, filtering, pagination, and many other features out of the box.',
    markdown:
      '### Features\n\n1. Sorting & Filtering\n2. Pagination\n3. Column resizing\n4. Row selection\n\n> The Data Grid is highly customizable!',
  },
];

const CharacterCountWrapper = styled('div')({
  display: 'flex',
  flexDirection: 'column',
  height: '100%',
});

const CharacterCountText = styled('span')(({ theme }) => ({
  marginTop: 'auto',
  paddingTop: theme.spacing(1),
  fontSize: '0.75rem',
  color: theme.palette.text.secondary,
}));

const MarkdownPreview = styled('div')(({ theme }) => ({
  fontFamily: theme.typography.fontFamily,
  '& h1, & h2, & h3': {
    marginTop: 0,
    marginBottom: theme.spacing(1),
    fontSize: '1rem',
    fontWeight: 600,
  },
  '& p': {
    marginTop: 0,
    marginBottom: theme.spacing(1),
  },
  '& ul, & ol': {
    marginTop: 0,
    marginBottom: theme.spacing(1),
    paddingLeft: theme.spacing(2),
  },
  '& code': {
    backgroundColor: theme.palette.action.hover,
    padding: theme.spacing(0.25, 0.5),
    borderRadius: theme.shape.borderRadius,
    fontSize: '0.85em',
  },
  '& pre': {
    backgroundColor: theme.palette.action.hover,
    padding: theme.spacing(1),
    borderRadius: theme.shape.borderRadius,
    overflow: 'auto',
    '& code': {
      backgroundColor: 'transparent',
      padding: 0,
    },
  },
  '& blockquote': {
    margin: 0,
    marginBottom: theme.spacing(1),
    paddingLeft: theme.spacing(1.5),
    borderLeft: `3px solid ${theme.palette.divider}`,
    color: theme.palette.text.secondary,
  },
  '& strong': {
    fontWeight: 600,
  },
  '& em': {
    fontStyle: 'italic',
  },
}));

const columns: GridColDef[] = [
  { field: 'title', headerName: 'Title', width: 180, rowHeader: true },
  {
    field: 'notes',
    headerName: 'Notes (with character count)',
    type: 'longText',
    width: 250,
    editable: true,
    renderCell: (params) => (
      <GridLongTextCell
        {...params}
        renderContent={(value) => (
          <CharacterCountWrapper>
            <div>{value}</div>
            <CharacterCountText>{value?.length ?? 0} characters</CharacterCountText>
          </CharacterCountWrapper>
        )}
      />
    ),
  },
  {
    field: 'markdown',
    headerName: 'Markdown (with preview)',
    type: 'longText',
    width: 250,
    editable: true,
    renderCell: (params) => (
      <GridLongTextCell
        {...params}
        renderContent={(value) => (
          <MarkdownPreview>
            <Markdown>{value ?? ''}</Markdown>
          </MarkdownPreview>
        )}
        slotProps={{
          popperContent: {
            style: {
              minWidth: 375,
              maxHeight: 'initial',
            },
          },
        }}
      />
    ),
  },
];

export default function LongTextCustomPopupContent() {
  return (
    <Box sx={{ height: 400, width: '100%' }}>
      <DataGrid rows={rows} columns={columns} />
    </Box>
  );
}

커스텀 다중 선택 칩

칩 모양을 커스터마이징하려면 GridMultiSelectCell과 GridEditMultiSelectCell 컴포넌트로 셀을 커스터마이징하세요. slotProps.chip에 함수를 전달해 각 값에서 칩 props를 도출할 수 있어요.

아래 데모는 두 가지 커스터마이징을 보여줘요:

  • 컬러 칩(Colored chips): 각 태그를 다른 칩 색상에 매핑해요
  • 아바타 칩(Avatar chips): 각 담당자 칩에 아바타를 추가해요
import * as React from 'react';
import Avatar from '@mui/material/Avatar';
import Box from '@mui/material/Box';
import Checkbox from '@mui/material/Checkbox';
import Chip, { ChipProps } from '@mui/material/Chip';
import {
  DataGridPro,
  GridColDef,
  GridMultiSelectCell,
  GridEditMultiSelectCell,
} from '@mui/x-data-grid-pro';
import { AutocompleteProps } from '@mui/x-data-grid/internals';

type ChipColor = NonNullable<ChipProps['color']>;

const tagColorMap: Record<string, ChipColor> = {
  Bug: 'error',
  Feature: 'primary',
  Enhancement: 'info',
  Documentation: 'warning',
  Performance: 'success',
};

const tagOptions = Object.keys(tagColorMap);

interface UserOption {
  value: string;
  label: string;
  avatar: string;
}

const departmentColors: Record<string, { bg: string; color: string }> = {
  Support: { bg: '#f0f0f0', color: '#555' },
  Sales: { bg: '#e8dff5', color: '#6b21a8' },
  Marketing: { bg: '#dbeafe', color: '#1e40af' },
  Product: { bg: '#fce7f3', color: '#9d174d' },
  DevEx: { bg: '#ffedd5', color: '#9a3412' },
  Design: { bg: '#fef9c3', color: '#854d0e' },
  'Engineering Management': { bg: '#e8e0d8', color: '#78716c' },
  Legal: { bg: '#dcfce7', color: '#166534' },
  Operations: { bg: '#e5e5e5', color: '#525252' },
  People: { bg: '#fef3c7', color: '#92400e' },
  Finance: { bg: '#dbeafe', color: '#1e3a8a' },
  Engineering: { bg: '#ffe4e6', color: '#be123c' },
};

const departmentOptions = Object.keys(departmentColors);

const userOptions: UserOption[] = [
  { value: 'alice', label: 'Alice', avatar: 'A' },
  { value: 'bob', label: 'Bob', avatar: 'B' },
  { value: 'charlie', label: 'Charlie', avatar: 'C' },
  { value: 'diana', label: 'Diana', avatar: 'D' },
  { value: 'eve', label: 'Eve', avatar: 'E' },
];

const rows = [
  {
    id: 1,
    title: 'Fix login crash',
    tags: ['Bug'],
    assignees: ['alice', 'bob'],
    departments: ['Engineering', 'Support'],
  },
  {
    id: 2,
    title: 'Add dark mode',
    tags: ['Feature', 'Enhancement'],
    assignees: ['charlie'],
    departments: ['Design', 'Product'],
  },
  {
    id: 3,
    title: 'Update API docs',
    tags: ['Documentation'],
    assignees: ['diana', 'eve'],
    departments: ['DevEx'],
  },
  {
    id: 4,
    title: 'Optimize queries',
    tags: ['Performance', 'Bug'],
    assignees: ['alice', 'eve', 'bob'],
    departments: ['Engineering', 'Operations'],
  },
];

const getTagChipProps = (value: string) => ({
  color: tagColorMap[value] ?? ('default' as ChipColor),
  variant: 'filled' as const,
});

const getAssigneeChipProps = (option: UserOption) => ({
  avatar: (
    <Avatar sx={{ width: 24, height: 24, fontSize: 12 }}>{option.avatar}</Avatar>
  ),
});

const getDepartmentChipProps = (value: string) => {
  const colors = departmentColors[value] ?? { bg: '#f0f0f0', color: '#555' };
  return {
    variant: 'filled' as const,
    sx: {
      backgroundColor: colors.bg,
      color: colors.color,
      fontWeight: 500,
      '& .MuiChip-deleteIcon': {
        color: colors.color,
        opacity: 0.6,
        '&:hover': { opacity: 1, color: colors.color },
      },
    },
  };
};

const renderDepartmentOption: NonNullable<
  AutocompleteProps<string>['renderOption']
> = (props, option, { selected }) => {
  const colors = departmentColors[option] ?? { bg: '#f0f0f0', color: '#555' };
  return (
    <li {...props}>
      <Checkbox checked={selected} sx={{ mr: 1, p: 0 }} />
      <Chip
        label={option}
        size="small"
        sx={{
          backgroundColor: colors.bg,
          color: colors.color,
          fontWeight: 500,
        }}
      />
    </li>
  );
};

const columns: GridColDef[] = [
  { field: 'title', headerName: 'Title', width: 160, rowHeader: true },
  {
    field: 'tags',
    headerName: 'Tags (colored)',
    type: 'multiSelect',
    width: 220,
    editable: true,
    valueOptions: tagOptions,
    renderCell: (params) => (
      <GridMultiSelectCell {...params} slotProps={{ chip: getTagChipProps }} />
    ),
    renderEditCell: (params) => (
      <GridEditMultiSelectCell {...params} slotProps={{ chip: getTagChipProps }} />
    ),
  },
  {
    field: 'assignees',
    headerName: 'Assignees (avatar)',
    type: 'multiSelect',
    width: 260,
    editable: true,
    valueOptions: userOptions,
    renderCell: (params) => (
      <GridMultiSelectCell {...params} slotProps={{ chip: getAssigneeChipProps }} />
    ),
    renderEditCell: (params) => (
      <GridEditMultiSelectCell
        {...params}
        slotProps={{ chip: getAssigneeChipProps }}
      />
    ),
  },
  {
    field: 'departments',
    headerName: 'Departments (custom options)',
    type: 'multiSelect',
    width: 280,
    editable: true,
    valueOptions: departmentOptions,
    renderCell: (params) => (
      <GridMultiSelectCell
        {...params}
        slotProps={{ chip: getDepartmentChipProps }}
      />
    ),
    renderEditCell: (params) => (
      <GridEditMultiSelectCell
        {...params}
        slotProps={{
          chip: getDepartmentChipProps,
          autocomplete: { renderOption: renderDepartmentOption },
        }}
      />
    ),
  },
];

export default function MultiSelectCustomChips() {
  return (
    <Box sx={{ height: 400, width: '100%' }}>
      <DataGridPro rows={rows} columns={columns} />
    </Box>
  );
}

더 알아보기 (Learn more)