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

Data Grid - 열 정의

원문 보기 위키 갱신

Data Grid - 열 정의 (Column definition)

열을 정의해볼게요. 열은 GridColDef[] 타입을 가진 columns prop으로 정의돼요.

field는 열 식별자이므로 유일한 필수 속성이에요. GridRowModel 값과 일치시키는 데도 사용돼요.

interface GridColDef {
  /**
   * The column identifier. It's used to match with [[GridRowModel]] values.
   */
  field: string;
  …
}
import Box from '@mui/material/Box';
import { DataGrid } from '@mui/x-data-grid';

export default function BasicColumnsGrid() {
  return (
    <Box sx={{ height: 250, width: '100%' }}>
      <DataGrid
        columns={[{ field: 'username', rowHeader: true }, { field: 'age' }]}
        rows={[
          {
            id: 1,
            username: '@MUI',
            age: 20,
          },
        ]}
      />
    </Box>
  );
}

:::warning columns prop은 두 렌더링 사이에 같은 참조를 유지해야 해요. 열은 정의(definition)로 설계되어 컴포넌트가 마운트되면 절대 변하지 않아야 해요. 그렇지 않으면 열 너비나 순서 같은 요소를 잃을 위험이 있어요. 배열을 렌더 함수 밖에서 만들거나 메모이즈하세요. :::

출처: MUI X documentation

본문

콘텐츠 제공하기

기본적으로 Data Grid는 열의 field를 사용해 값을 가져와요. 예를 들어 field가 name인 열은 row.name에 저장된 값을 렌더링해요. 하지만 일부 열에서는 렌더링할 값을 직접 가져와 형식화하는 것이 유용할 수 있어요.

값 게터 (Value getter)

:::warning valueGetter의 시그니처는 v7에서 변경되었어요 — 자세한 내용은 마이그레이션 가이드를 참고하세요.

v6를 사용 중이라면 v6 문서를 사용해주세요. :::

때로는 열에 원하는 값이 없을 수 있어요. GridColDef의 valueGetter 속성을 사용해 다음과 같이 할 수 있어요.

  1. 값 변환하기

    const columns: GridColDef[] = [
      {
        field: 'taxRate',
        valueGetter: (value) => {
          if (!value) {
            return value;
          }
          // Convert the decimal value to a percentage
          return value * 100;
        },
      },
    ];
    
  2. 서로 다른 필드의 조합 렌더링하기

    const columns: GridColDef[] = [
      {
        field: 'fullName',
        valueGetter: (value, row) => {
          return `${row.firstName || ''} ${row.lastName || ''}`;
        },
      },
    ];
    
  3. 복잡한 값에서 값 파생하기

    const columns: GridColDef[] = [
      {
        field: 'profit',
        valueGetter: (value, row) => {
          if (!row.gross || !row.costs) {
            return null;
          }
          return row.gross - row.costs;
        },
      },
    ];
    

valueGetter가 반환한 값은 다음에 사용돼요.

import Box from '@mui/material/Box';
import { DataGrid, GridColDef, GridValueGetter } from '@mui/x-data-grid';

const rows = [
  { id: 1, lastName: 'Snow', firstName: 'Jon' },
  { id: 2, lastName: 'Lannister', firstName: 'Cersei' },
  { id: 3, lastName: 'Lannister', firstName: 'Jaime' },
  { id: 4, lastName: 'Stark', firstName: 'Arya' },
  { id: 5, lastName: 'Targaryen', firstName: 'Daenerys' },
];

const getFullName: GridValueGetter<(typeof rows)[number], unknown> = (
  value,
  row,
) => {
  return `${row.firstName || ''} ${row.lastName || ''}`;
};

const columns: GridColDef[] = [
  { field: 'firstName', headerName: 'First name', width: 130 },
  { field: 'lastName', headerName: 'Last name', width: 130 },
  {
    field: 'fullName',
    headerName: 'Full name',
    rowHeader: true,
    width: 160,
    valueGetter: getFullName,
  },
];

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

:::warning valueGetter는 행 그룹화나 집계 같은 기능을 사용할 때 만들어지는 자동 생성 행(autogenerated rows)에서도 호출될 수 있어요. 자동 생성 행 처리 절에서 자세한 내용을 확인하세요. :::

:::warning 행 그룹화는 그룹화 값을 얻기 위해 valueGetter 대신 groupingValueGetter()를 사용해요. groupingValueGetter()에 전달되는 값은 열 정의에 valueGetter가 정의되어 있어도 원시 행 값(row[field])이에요. :::

값 포맷터 (Value formatter)

:::warning valueFormatter의 시그니처는 v7에서 변경되었어요 — 자세한 내용은 마이그레이션 가이드를 참고하세요.

v6를 사용 중이라면 v6 문서를 사용해주세요. :::

값 포맷터는 값을 표시하기 전에 변환할 수 있게 해줘요. 일반적인 사용 사례로는 JavaScript Date 객체를 날짜 문자열로 변환하거나, Number를 형식화된 숫자(예: "1,000.50")로 변환하는 것이 있어요.

valueFormatter가 반환한 값은 렌더링 목적으로만 사용된다는 점에 유의하세요. 필터링과 정렬은 원시 값(row[field]) 또는 valueGetter가 반환한 값을 기준으로 해요.

다음 데모에서는 valueGetter가 세율(예: 0.2)을 십진수 값(예: 20)으로 변환하고, valueFormatter가 이를 백분율(예: 20%)로 표시해요.

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

const rows = [
  {
    id: 1,
    taxRate: 0.1,
  },
  {
    id: 2,
    taxRate: 0.2,
  },
  {
    id: 3,
    taxRate: 0.3,
  },
];

export default function ValueFormatterGrid() {
  return (
    <div style={{ height: 300, width: '100%' }}>
      <DataGrid
        rows={rows}
        columns={[
          {
            type: 'number',
            field: 'taxRate',
            headerName: 'Tax Rate',
            width: 150,
            valueGetter: (value) => {
              if (!value) {
                return value;
              }
              return value * 100;
            },
            valueFormatter: (value?: number) => {
              if (value == null) {
                return '';
              }
              return `${value.toLocaleString()} %`;
            },
          },
        ]}
      />
    </div>
  );
}

:::warning valueFormatter는 행 그룹화나 집계 같은 기능을 사용할 때 만들어지는 자동 생성 행에서도 호출될 수 있어요. 자동 생성 행 처리 절에서 자세한 내용을 확인하세요. :::

셀 렌더링

기본적으로 Data Grid는 셀에 값을 문자열로 렌더링해요. 렌더링 출력은 다음 순서로 해석돼요.

  1. renderCell() => ReactElement
  2. valueFormatter() => string
  3. valueGetter() => string
  4. row[field]

열 정의의 renderCell() 메서드는 valueFormatter()와 비슷해요. 하지만 셀에서만 렌더링할 수 있다는 제한 대신, 문자열 대신 React 노드를 반환할 수 있게 해줘요.

const columns: GridColDef[] = [
  {
    field: 'date',
    headerName: 'Year',
    renderCell: (params: GridRenderCellParams<any, Date>) => (
      <strong>
        {params.value.getFullYear()}
        <Button
          variant="contained"
          size="small"
          style={{ marginLeft: 16 }}
          tabIndex={params.hasFocus ? 0 : -1}
        >
          Open
        </Button>
      </strong>
    ),
  },
];
import * as React from 'react';
import Button from '@mui/material/Button';
import { DataGrid, GridColDef, GridRenderCellParams } from '@mui/x-data-grid';
import { TouchRippleActions } from '@mui/material/ButtonBase/TouchRipple';

function RenderDate(props: GridRenderCellParams<any, Date>) {
  const { hasFocus, value } = props;
  const buttonElement = React.useRef<HTMLButtonElement>(null);
  const rippleRef = React.useRef<TouchRippleActions>(null);

  React.useLayoutEffect(() => {
    if (hasFocus) {
      const input = buttonElement.current!.querySelector('input');
      input?.focus();
    } else if (rippleRef.current) {
      // Only available in @mui/material v5.4.1 or later
      rippleRef.current.stop({} as any);
    }
  }, [hasFocus]);

  return (
    <strong>
      {value?.getFullYear() ?? ''}
      <Button
        ref={buttonElement}
        touchRippleRef={rippleRef}
        variant="contained"
        size="small"
        style={{ marginLeft: 16 }}
        // Remove button from tab sequence when cell does not have focus
        tabIndex={hasFocus ? 0 : -1}
        onKeyDown={(event: React.KeyboardEvent) => {
          if (event.key === ' ') {
            // Prevent key navigation when focus is on button
            event.stopPropagation();
          }
        }}
      >
        Open
      </Button>
    </strong>
  );
}

const columns: GridColDef[] = [
  {
    field: 'date',
    headerName: 'Year',
    rowHeader: true,
    width: 150,
    renderCell: RenderDate,
  },
];

const rows = [
  {
    id: 1,
    date: new Date(1979, 0, 1),
  },
  {
    id: 2,
    date: new Date(1984, 1, 1),
  },
  {
    id: 3,
    date: new Date(1992, 2, 1),
  },
];

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

:::warning renderCell()을 사용할 때, valueGetter()가 반환한 값의 타입이 열의 type과 일치하지 않으면 다음을 해야 해요.

  • 열에 sortComparator를 제공해 정렬을 처리하고,
  • 데이터 내보내기 시 사용할 값의 표현을 제공하는 valueFormatter를 설정하세요.

:::

:::warning renderCell()은 행 그룹화나 집계 같은 기능을 사용할 때 만들어지는 자동 생성 행에서도 호출될 수 있어요. 자동 생성 행 처리 절에서 자세한 내용을 확인하세요. :::

셀 스타일링

자세한 내용은 셀 스타일링 절을 참고하세요.

접근성 좋은 셀 만들기

셀 콘텐츠는 셀이 포커스된 경우를 제외하면 탭 시퀀스에 있어서는 안 돼요. 자세한 내용은 탭 시퀀스 절을 참고하세요.

열에 각 행을 식별하는 레이블이 포함되어 있으면, 열 정의에 rowHeader: true를 설정하세요. 그러면 셀에 rowheader ARIA 역할이 부여되어, 사용자가 그리드를 탐색하는 동안 스크린 리더가 행 레이블을 읽을 수 있어요. 자세한 내용은 행 헤더 절을 참고하세요.

렌더러 안에서 훅 사용하기

renderCell() 속성은 React 컴포넌트가 아니라 React 노드를 반환하는 함수예요.

렌더러 안에서 React 훅을 사용하고 싶다면, 훅을 컴포넌트 안에 감싸야 해요.

// ❌ Not valid
const column = {
  // ...other properties,
  renderCell: () => {
    const [count, setCount] = React.useState(0);

    return (
      <Button onClick={() => setCount((prev) => prev + 1)}>{count} click(s)</Button>
    );
  },
};

// ✅ Valid
const CountButton = () => {
  const [count, setCount] = React.useState(0);

  return (
    <Button onClick={() => setCount((prev) => prev + 1)}>{count} click(s)</Button>
  );
};

const column = {
  // ...other properties,
  renderCell: () => <CountButton />,
};

:::warning 페이지네이션과 가상화 때문에 셀은 스크롤하거나 페이지를 전환할 때 언마운트될 수 있어요. renderCell이 반환한 컴포넌트의 내부 상태는 사라져요.

셀 정보를 유지하려면, Data Grid 상태나 Data Grid 부모에 저장해야 해요. :::

셀 렌더러 확장하기

기본적으로 Data Grid는 셀의 콘텐츠를 잘라내고, 셀 콘텐츠가 셀에 맞지 않으면 말줄임표(ellipsis)를 렌더링해요. 해결 방법으로, 사용자가 Data Grid에서 셀의 전체 콘텐츠를 볼 수 있는 셀 렌더러를 만들 수 있어요.

import * as React from 'react';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import Paper from '@mui/material/Paper';
import Popper from '@mui/material/Popper';
import { DataGrid, GridColDef, GridRenderCellParams } from '@mui/x-data-grid';

interface GridCellExpandProps {
  value: string;
  width: number;
}

function isOverflown(element: Element): boolean {
  return (
    element.scrollHeight > element.clientHeight ||
    element.scrollWidth > element.clientWidth
  );
}

const GridCellExpand = React.memo(function GridCellExpand(
  props: GridCellExpandProps,
) {
  const { width, value } = props;
  const wrapper = React.useRef<HTMLDivElement | null>(null);
  const cellDiv = React.useRef(null);
  const cellValue = React.useRef(null);
  const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
  const [showFullCell, setShowFullCell] = React.useState(false);
  const [showPopper, setShowPopper] = React.useState(false);

  const handleMouseEnter = () => {
    const isCurrentlyOverflown = isOverflown(cellValue.current!);
    setShowPopper(isCurrentlyOverflown);
    setAnchorEl(cellDiv.current);
    setShowFullCell(true);
  };

  const handleMouseLeave = () => {
    setShowFullCell(false);
  };

  React.useEffect(() => {
    if (!showFullCell) {
      return undefined;
    }

    function handleKeyDown(nativeEvent: KeyboardEvent) {
      if (nativeEvent.key === 'Escape') {
        setShowFullCell(false);
      }
    }

    document.addEventListener('keydown', handleKeyDown);

    return () => {
      document.removeEventListener('keydown', handleKeyDown);
    };
  }, [setShowFullCell, showFullCell]);

  return (
    <Box
      ref={wrapper}
      onMouseEnter={handleMouseEnter}
      onMouseLeave={handleMouseLeave}
      sx={{
        alignItems: 'center',
        lineHeight: '24px',
        width: '100%',
        height: '100%',
        position: 'relative',
        display: 'flex',
      }}
    >
      <Box
        ref={cellDiv}
        sx={{
          height: '100%',
          width,
          display: 'block',
          position: 'absolute',
          top: 0,
        }}
      />
      <Box
        ref={cellValue}
        sx={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}
      >
        {value}
      </Box>
      {showPopper && (
        <Popper
          open={showFullCell && anchorEl !== null}
          anchorEl={anchorEl}
          style={{ width, marginLeft: -17 }}
        >
          <Paper
            elevation={1}
            style={{ minHeight: wrapper.current!.offsetHeight - 3 }}
          >
            <Typography variant="body2" style={{ padding: 8 }}>
              {value}
            </Typography>
          </Paper>
        </Popper>
      )}
    </Box>
  );
});

function renderCellExpand(params: GridRenderCellParams<any, string>) {
  return (
    <GridCellExpand value={params.value || ''} width={params.colDef.computedWidth} />
  );
}

const columns: GridColDef[] = [
  { field: 'col1', headerName: 'Column 1', width: 80, renderCell: renderCellExpand },
  {
    field: 'col2',
    headerName: 'Column 2',
    width: 100,
    renderCell: renderCellExpand,
  },
  {
    field: 'col3',
    headerName: 'Column 3',
    width: 150,
    renderCell: renderCellExpand,
  },
];
const rows: any = [
  {
    id: 1,
    col1: 'Hello',
    col2: 'World',
    col3: 'In publishing and graphic design, Lorem ipsum is a placeholder text commonly used.',
  },
  {
    id: 2,
    col1: 'DataGridPro',
    col2: 'is Awesome',
    col3: 'In publishing and graphic design, Lorem ipsum is a placeholder text or a typeface without relying on meaningful content. Lorem ipsum may be used as a placeholder before final copy is available.',
  },
  {
    id: 3,
    col1: 'MUI',
    col2: 'is Amazing',
    col3: 'Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document or a typeface without relying on meaningful content. Lorem ipsum may be used as a placeholder before final copy is available.',
  },
  {
    id: 4,
    col1: 'Hello',
    col2: 'World',
    col3: 'In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form.',
  },
  {
    id: 5,
    col1: 'DataGridPro',
    col2: 'is Awesome',
    col3: 'Typeface without relying on meaningful content. Lorem ipsum may be used as a placeholder before final copy is available.',
  },
  {
    id: 6,
    col1: 'MUI',
    col2: 'is Amazing',
    col3: 'Lorem ipsum may be used as a placeholder before final copy is available.',
  },
];

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

:::warning 페이지네이션과 가상화 때문에 셀은 스크롤하거나 페이지를 전환할 때 언마운트될 수 있어요. renderCell()이 반환한 컴포넌트의 내부 상태는 사라져요.

셀 정보를 유지하려면, Data Grid 부모나 행 모델에 저장해야 해요. 행을 업데이트하면 행이 다시 렌더링되므로 업데이트된 params로 renderCell이 호출돼요. :::

열 타입

열 구성을 쉽게 하기 위해 몇 가지 열 타입이 미리 정의되어 있어요. 기본적으로 열은 문자열을 가진다고 가정하므로, 기본 문자열 타입이 적용돼요. 그 결과 열 정렬은 문자열 비교기를 사용하고, 열 콘텐츠는 셀 왼쪽에 정렬돼요. 일부 열 타입은 해당 값이 특정 타입이어야 해요.

다음은 값 타입이 필요한 네이티브 열 타입이에요.

Column type Value type
'string' (default) string
'longText' string
'number' number
'date' Date() object
'dateTime' Date() object
'boolean' boolean
'singleSelect' A value in .valueOptions
'multiSelect' An array of values in .valueOptions
'actions' Not applicable
import * as React from 'react';
import {
  DataGrid,
  GridActionsCellItem,
  GridRowId,
  GridColDef,
  GridActionsCell,
  GridRenderCellParams,
} from '@mui/x-data-grid';
import DeleteIcon from '@mui/icons-material/Delete';
import SecurityIcon from '@mui/icons-material/Security';
import FileCopyIcon from '@mui/icons-material/FileCopy';
import { randomCreatedDate, randomUpdatedDate } from '@mui/x-data-grid-generator';

const initialRows = [
  {
    id: 1,
    name: 'Damien',
    age: 25,
    dateCreated: randomCreatedDate(),
    lastLogin: randomUpdatedDate(),
    isAdmin: true,
    country: 'Spain',
    discount: '',
    bio: 'Damien is a software engineer with 5 years of experience in web development. He specializes in React and Node.js.',
  },
  {
    id: 2,
    name: 'Nicolas',
    age: 36,
    dateCreated: randomCreatedDate(),
    lastLogin: randomUpdatedDate(),
    isAdmin: false,
    country: 'France',
    discount: '',
    bio: 'Nicolas is a product manager who loves building user-centric products. He has led multiple successful product launches.',
  },
  {
    id: 3,
    name: 'Kate',
    age: 19,
    dateCreated: randomCreatedDate(),
    lastLogin: randomUpdatedDate(),
    isAdmin: false,
    country: 'Brazil',
    discount: 'junior',
    bio: 'Kate is a junior developer passionate about learning new technologies. She is currently focused on frontend development.',
  },
];

type Row = (typeof initialRows)[number];

interface ActionHandlers {
  deleteUser: (id: GridRowId) => void;
  toggleAdmin: (id: GridRowId) => void;
  duplicateUser: (id: GridRowId) => void;
}

const ActionHandlersContext = React.createContext<ActionHandlers>({
  deleteUser: () => {},
  toggleAdmin: () => {},
  duplicateUser: () => {},
});

function ActionsCell(props: GridRenderCellParams) {
  const { deleteUser, toggleAdmin, duplicateUser } =
    React.useContext(ActionHandlersContext);

  return (
    <GridActionsCell {...props}>
      <GridActionsCellItem
        icon={<DeleteIcon />}
        label="Delete"
        onClick={() => deleteUser(props.id)}
      />
      <GridActionsCellItem
        icon={<SecurityIcon />}
        label="Toggle Admin"
        onClick={() => toggleAdmin(props.id)}
        showInMenu
      />
      <GridActionsCellItem
        icon={<FileCopyIcon />}
        label="Duplicate User"
        onClick={() => duplicateUser(props.id)}
        showInMenu
      />
    </GridActionsCell>
  );
}

const columns: GridColDef<Row>[] = [
  { field: 'name', type: 'string', rowHeader: true },
  {
    field: 'bio',
    type: 'longText',
    width: 200,
  },
  { field: 'age', type: 'number' },
  { field: 'dateCreated', type: 'date', width: 130 },
  { field: 'lastLogin', type: 'dateTime', width: 180 },
  { field: 'isAdmin', type: 'boolean', width: 120 },
  {
    field: 'country',
    type: 'singleSelect',
    width: 120,
    valueOptions: [
      'Bulgaria',
      'Netherlands',
      'France',
      'United Kingdom',
      'Spain',
      'Brazil',
    ],
  },
  {
    field: 'discount',
    type: 'singleSelect',
    width: 120,
    editable: true,
    valueOptions: ({ row }) => {
      if (row === undefined) {
        return ['EU-resident', 'junior'];
      }
      const options: string[] = [];
      if (!['United Kingdom', 'Brazil'].includes(row.country)) {
        options.push('EU-resident');
      }
      if (row.age < 27) {
        options.push('junior');
      }
      return options;
    },
  },
  {
    field: 'actions',
    type: 'actions',
    width: 80,
    renderCell: (params) => <ActionsCell {...params} />,
  },
];

export default function ColumnTypesGrid() {
  const [rows, setRows] = React.useState<Row[]>(initialRows);

  const deleteUser = React.useCallback((id: GridRowId) => {
    setTimeout(() => {
      setRows((prevRows) => prevRows.filter((row) => row.id !== id));
    });
  }, []);

  const toggleAdmin = React.useCallback((id: GridRowId) => {
    setRows((prevRows) =>
      prevRows.map((row) =>
        row.id === id ? { ...row, isAdmin: !row.isAdmin } : row,
      ),
    );
  }, []);

  const duplicateUser = React.useCallback((id: GridRowId) => {
    setRows((prevRows) => {
      const rowToDuplicate = prevRows.find((row) => row.id === id)!;
      return [...prevRows, { ...rowToDuplicate, id: Date.now() }];
    });
  }, []);

  const actionHandlers = React.useMemo<ActionHandlers>(
    () => ({
      deleteUser,
      toggleAdmin,
      duplicateUser,
    }),
    [deleteUser, toggleAdmin, duplicateUser],
  );

  return (
    <div style={{ height: 300, width: '100%' }}>
      <ActionHandlersContext.Provider value={actionHandlers}>
        <DataGrid columns={columns} rows={rows} />
      </ActionHandlersContext.Provider>
    </div>
  );
}

긴 텍스트 키보드 상호작용

'longText' 열 타입은 클릭 또는 키보드 내비게이션으로 셀이 포커스되었을 때 콘텐츠를 펼치고(expand), 접고(collapse), 편집할 수 있는 키보드 상호작용을 지원해요.

보기 모드 (확장 버튼 포커스됨):

  • Space – 팝업 토글
  • Escape – 팝업 닫기

편집 모드 (textarea 포커스됨):

  • Shift+Enter – 새 줄 삽입
  • Enter – 변경 사항 커밋
  • Escape – 편집 취소

다중 선택 키보드 상호작용

'multiSelect' 열 타입은 클릭 또는 키보드 내비게이션으로 셀이 포커스되었을 때 넘치는 칩을 펼치고 값을 편집할 수 있는 키보드 상호작용을 지원해요.

보기 모드 (셀 포커스됨):

  • Space – 모든 값을 보려면 넘침 팝업 토글
  • Escape – 팝업 닫기
  • Enter 또는 F2 – 편집 모드 진입

편집 모드 (자동완성 포커스됨):

  • Arrow Up/Arrow Down – 옵션 탐색
  • Ctrl+Enter (macOS에서는 Cmd+Enter) – 강조된 옵션 선택/해제 (드롭다운은 열린 채 유지)
  • Enter – 변경 사항 커밋하고 편집 모드 종료
  • Escape – 편집 취소하고 드롭다운 닫기
  • Backspace (빈 입력) – 마지막 선택 칩 제거
import * as React from 'react';
import { DataGridPro, GridColDef } from '@mui/x-data-grid-pro';

const rows = [
  { id: 1, project: 'Alpha', skills: ['React', 'TypeScript'] },
  { id: 2, project: 'Beta', skills: ['Node.js', 'GraphQL', 'TypeScript'] },
  { id: 3, project: 'Gamma', skills: [] },
  { id: 4, project: 'Delta', skills: ['React', 'JavaScript', 'Node.js'] },
];

const columns: GridColDef[] = [
  { field: 'project', headerName: 'Project', width: 120, rowHeader: true },
  {
    field: 'skills',
    headerName: 'Skills',
    type: 'multiSelect',
    width: 250,
    editable: true,
    valueOptions: [
      'React',
      'TypeScript',
      'JavaScript',
      'Node.js',
      'GraphQL',
      'REST',
    ],
  },
];

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

타입 변환하기

필터링, 정렬 같은 기본 메서드는 값의 타입이 type에 지정된 열 타입과 일치한다고 가정해요. 예를 들어 type: 'dateTime'인 열의 값은 Date() 객체로 저장될 것으로 기대해요. 어떤 이유로든 데이터 타입이 올바르지 않다면, valueGetter를 사용해 값을 올바른 타입으로 파싱할 수 있어요.

{
  field: 'lastLogin',
  type: 'dateTime',
  valueGetter: (value) => value && new Date(value),
}

특수 속성 (Special properties)

대부분의 열 타입을 사용하려면 열 정의에 type 속성만 정의하면 돼요. 하지만 일부 타입은 제대로 작동하기 위해 추가 속성이 필요해요.

단일 선택 (Single select)

열 타입이 'singleSelect'라면, 해당 열 정의에 valueOptions 속성도 설정해야 해요. 이 값들은 필터링과 편집에 사용되는 옵션이에요.

{
  field: 'country',
  type: 'singleSelect',
  valueOptions: ['United Kingdom', 'Spain', 'Brazil']
}

:::warning valueOptions에 객체 값을 사용할 때는 각 옵션에 value와 label 속성을 제공해야 해요. 하지만 getOptionValue()와 getOptionLabel()을 사용하면 어떤 속성을 값과 레이블로 사용할지 커스터마이즈할 수 있어요.

// Without getOptionValue and getOptionLabel
{
  valueOptions: [
    { value: 'BR', label: 'Brazil' },
    { value: 'FR', label: 'France' }
  ]
}

// With getOptionValue and getOptionLabel
{
  getOptionValue: (value: any) => value.code,
  getOptionLabel: (value: any) => value.name,
  valueOptions: [
    { code: 'BR', name: 'Brazil' },
    { code: 'FR', name: 'France' }
  ]
}

:::

다중 선택 (Multi select)

:::info 'multiSelect' 열 타입은 Pro 및 Premium 요금제에서 사용할 수 있어요. Community 요금제에서는 'string' 열 타입으로 대체돼요. :::

열 타입이 'multiSelect'라면, singleSelect와 비슷하게 valueOptions 속성을 설정해야 해요. 셀 값은 옵션의 값 배열이어야 해요.

{
  field: 'tags',
  type: 'multiSelect',
  valueOptions: ['React', 'TypeScript', 'JavaScript', 'Node.js']
}

multiSelect 열은 값을 칩으로 표시하고, 열이 좁을 때는 넘침을 처리해요. 사용자는 다중 선택 자동완성 드롭다운으로 셀을 편집할 수 있어요.

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

const rows = [
  {
    id: 1,
    name: 'Project Alpha',
    tags: ['React', 'TypeScript'],
    categories: ['fe'],
  },
  {
    id: 2,
    name: 'Project Beta',
    tags: ['Node.js', 'GraphQL', 'TypeScript'],
    categories: ['be', 'db'],
  },
  {
    id: 3,
    name: 'Project Gamma',
    tags: [],
    categories: ['infra'],
  },
  {
    id: 4,
    name: 'Project Delta',
    tags: ['React', 'JavaScript', 'REST', 'Node.js'],
    categories: ['fe', 'be'],
  },
];

const columns: GridColDef[] = [
  { field: 'name', headerName: 'Project', width: 130, rowHeader: true },
  {
    field: 'tags',
    headerName: 'Tags',
    type: 'multiSelect',
    width: 200,
    editable: true,
    valueOptions: [
      'React',
      'TypeScript',
      'JavaScript',
      'Node.js',
      'GraphQL',
      'REST',
    ],
  },
  {
    field: 'categories',
    headerName: 'Categories',
    type: 'multiSelect',
    width: 180,
    editable: true,
    valueOptions: [
      { value: 'fe', label: 'Frontend' },
      { value: 'be', label: 'Backend' },
      { value: 'db', label: 'Database' },
      { value: 'infra', label: 'Infrastructure' },
    ],
  },
];

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

액션 (Actions)

열 타입이 'actions'라면, GridActionsCell 컴포넌트를 자식으로 GridActionsCellItem 요소와 함께 렌더링하는 renderCell() 함수를 제공해야 해요. GridActionsCellItem 요소에 showInMenu prop을 추가하면 Data Grid가 이 액션들을 행 메뉴 안에 그룹화하도록 지시할 수 있어요.

{
  field: 'actions',
  type: 'actions',
  renderCell: (params) => (
    <GridActionsCell {...params}>
      <GridActionsCellItem icon={...} onClick={...} label="Delete" />
      <GridActionsCellItem icon={...} onClick={...} label="Print" showInMenu />
    </GridActionsCell>
  )
}

:::warning 이것은 v8.19.0부터 열 정의에서 액션을 정의하는 권장 방식이에요. 액션 배열을 반환하던 getActions() 메서드는 더 이상 사용되지 않으며(현재는 deprecated), 향후 버전에서 제거될 예정이에요. :::

액션을 링크로 렌더링하려면 GridActionsCellItem에 href prop을 전달하세요. 그러면 액션이 앵커 태그로 렌더링되어, 키보드로 접근 가능하고 스크린 리더가 올바르게 알려줘요. 새 탭에서 링크를 열려면 target="_blank"를 추가하고, 보안 문제를 피하려면 rel="noopener noreferrer"를 설정하세요.

<GridActionsCellItem
  icon={...}
  label="Open details"
  href={`/details/${params.id}`}
  target="_blank"
  rel="noopener noreferrer"
  showInMenu
/>

기본적으로 메뉴에 표시된 액션은 클릭 시 메뉴를 닫아요. 하지만 어떤 경우에는 액션을 클릭한 후에도 메뉴를 열어두고 싶을 수 있어요. closeMenuOnClick prop을 false로 설정하면 이를 구현할 수 있어요.

다음 예제에서 "Delete" 액션은 확인 다이얼로그를 열므로 메뉴를 마운트된 상태로 유지해야 해요.

import * as React from 'react';
import {
  DataGrid,
  GridActionsCellItem,
  GridRowId,
  GridColDef,
  GridActionsCell,
  GridRenderCellParams,
} from '@mui/x-data-grid';
import DeleteIcon from '@mui/icons-material/Delete';
import { randomUserName } from '@mui/x-data-grid-generator';
import Dialog from '@mui/material/Dialog';
import DialogTitle from '@mui/material/DialogTitle';
import DialogContent from '@mui/material/DialogContent';
import DialogContentText from '@mui/material/DialogContentText';
import DialogActions from '@mui/material/DialogActions';
import Button from '@mui/material/Button';

const initialRows = [
  { id: 1, name: randomUserName() },
  { id: 2, name: randomUserName() },
  { id: 3, name: randomUserName() },
];

type Row = (typeof initialRows)[number];

const ActionHandlersContext = React.createContext<
  ((id: GridRowId) => void) | undefined
>(undefined);

function ActionsCell(props: GridRenderCellParams) {
  const setActionRowId = React.useContext(ActionHandlersContext);

  if (!setActionRowId) {
    throw new Error('ActionHandlersContext is empty');
  }

  return (
    <GridActionsCell {...props}>
      <GridActionsCellItem
        label="Delete"
        showInMenu
        icon={<DeleteIcon />}
        onClick={() => setActionRowId(props.id)}
        closeMenuOnClick={false}
      />
    </GridActionsCell>
  );
}

const columns: GridColDef<Row>[] = [
  { field: 'name', type: 'string', rowHeader: true },
  {
    field: 'actions',
    type: 'actions',
    width: 80,
    renderCell: (params) => <ActionsCell {...params} />,
  },
];

export default function ActionsWithModalGrid() {
  const [rows, setRows] = React.useState<Row[]>(initialRows);
  const [actionRowId, setActionRowId] = React.useState<GridRowId | null>(null);

  const deleteActiveRow = React.useCallback(
    (rowId: GridRowId) =>
      setRows((prevRows) => prevRows.filter((row) => row.id !== rowId)),
    [],
  );

  const handleCloseDialog = React.useCallback(() => {
    setActionRowId(null);
  }, []);

  const handleConfirmDelete = React.useCallback(() => {
    deleteActiveRow(actionRowId!);
    handleCloseDialog();
  }, [actionRowId, deleteActiveRow, handleCloseDialog]);

  return (
    <div style={{ height: 300, width: '100%' }}>
      <ActionHandlersContext.Provider value={setActionRowId}>
        <DataGrid columns={columns} rows={rows} />
      </ActionHandlersContext.Provider>
      <Dialog
        open={actionRowId !== null}
        onClose={handleCloseDialog}
        aria-labelledby="alert-dialog-title"
        aria-describedby="alert-dialog-description"
      >
        <DialogTitle id="alert-dialog-title">Delete this user?</DialogTitle>
        <DialogContent>
          <DialogContentText id="alert-dialog-description">
            This action cannot be undone.
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseDialog}>Cancel</Button>
          <Button onClick={handleConfirmDelete} color="warning" autoFocus>
            Delete
          </Button>
        </DialogActions>
      </Dialog>
    </div>
  );
}

:::success 위 예제에서는 React Context API를 사용해 액션 핸들러를 ActionsCell 컴포넌트에 전달해요. 이것은 열 정의를 안정적으로 유지하기 위한 권장 패턴이에요. :::

커스텀 열 타입

문서와 통합 예제는 커스텀 열 페이지를 참고하세요.

자동 생성 행 (Autogenerated rows)

행 그룹화나 집계 같은 일부 기능은 자동 생성 행을 만들어요. 이 행들도 valueGetter(), valueFormatter(), renderCell() 같은 함수를 호출하는데, row 파라미터가 빈 객체이고 value 파라미터가 undefined라서 예상치 못한 문제가 생길 수 있어요. 영화 데이터셋을 예로 들면, isAutogeneratedRow()로 자동 생성 행을 감지할 수 있어요.

{
  field: 'title',
  valueGetter: (value, row) => {
    if (isAutogeneratedRow(row)) {
      return '[this is an autogenerated row]';
    }
    return `title: ${value}`;
  },
}
import {
  DataGridPremium,
  GRID_ROW_GROUPING_SINGLE_GROUPING_FIELD,
  GridColDef,
  isAutogeneratedRow,
  useGridApiRef,
  useKeepGroupedColumnsHidden,
} from '@mui/x-data-grid-premium';
import { useMovieData } from '@mui/x-data-grid-generator';

const columns: GridColDef[] = [
  { field: GRID_ROW_GROUPING_SINGLE_GROUPING_FIELD, width: 200 },
  { field: 'company', width: 200 },
  {
    field: 'title',
    minWidth: 250,
    cellClassName: 'highlighted',
    valueGetter: (value, row) => {
      if (isAutogeneratedRow(row)) {
        return '[this is an autogenerated row]';
      }
      return `title: ${value}`;
    },
  },
  { field: 'year' },
];

export default function AutogeneratedRows() {
  const { rows } = useMovieData();
  const apiRef = useGridApiRef();

  const initialState = useKeepGroupedColumnsHidden({
    apiRef,
    initialState: {
      rowGrouping: {
        model: ['company'],
      },
    },
  });

  return (
    <div style={{ height: 400, width: '100%' }}>
      <DataGridPremium
        rows={rows}
        columns={columns}
        apiRef={apiRef}
        initialState={initialState}
        defaultGroupingExpansionDepth={-1}
        sx={{
          '.MuiDataGrid-cell:not(.highlighted)': {
            color: '#999',
          },
        }}
      />
    </div>
  );
}

셀렉터 (Selectors)

표시되는 열 (Visible columns)

이 셀렉터들은 숨겨진 열을 고려하지 않아요.

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

정의된 열 (Defined columns)

이 셀렉터들은 숨겨진 열을 포함한 모든 정의된 열을 고려해요.

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

셀렉터와 사용 방법에 대한 자세한 내용은 전용 페이지를 참고하세요.

API

더 알아보기 (Learn more)