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

Data Grid - 셀

원문 보기 위키 갱신

Data Grid - 셀 (Cells)

셀의 렌더링된 요소와 값을 커스터마이즈하는 방법을 알아봅니다.

셀 커스터마이즈

Data Grid는 renderCell(), valueGetter(), valueFormatter()를 포함해 셀의 렌더링된 요소와 값을 커스터마이즈하는 여러 방법을 제공합니다. 이 문서는 각 방법의 핵심적인 차이점과 구체적인 사용 사례를 설명합니다.

renderCell()

renderCell() 함수를 사용하여 셀 안에 어떤 요소든 렌더링할 수 있습니다. 이 방법은 셀 안에 React 컴포넌트를 렌더링하는 유일한 방법이며, 셀의 동작(예: 클릭 핸들러 추가)을 커스터마이즈하는 유일한 방법이기도 합니다.

강력하기는 하지만 성능 면에서 비용이 들기 때문에, 특정 사용 사례를 구현할 다른 방법이 없을 때 최후의 수단으로만 사용해야 합니다.

다음은 renderCell()을 사용해 버튼을 렌더링하는 셀의 예시입니다:

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>
    ),
  },
];

자세한 내용은 Column 정의—셀 렌더링을 참고하세요.

valueGetter()

valueGetter() 함수를 사용하여 행 데이터에서 셀의 값을 파생할 수 있습니다. 이 방법은 셀 내용을 커스터마이즈하는 가장 성능이 좋은 방법이며, 행 데이터 자체를 변경하지 않고도 처리합니다.

일반적인 사용 사례는 다음과 같습니다:

  • 값 변환 (예: 소수 값을 백분율 값으로 변환)
  • 여러 필드에서 값 파생 (예: 이름(first name)과 성(last name) 연결)
  • 중첩 필드에서 값 파생 (예: user.address.city)

이 함수는 Data Grid 내부에서도 필터링, 정렬, 렌더링(renderCell() 또는 valueFormatter()가 제공되지 않을 때)에 사용됩니다.

자세한 내용은 Column 정의—Value getter를 참고하세요.

valueFormatter()

valueFormatter() 함수를 사용하여 셀의 값을 표시 형식화할 수 있습니다 (기본 행 데이터는 변경하지 않습니다).

일반적인 사용 사례는 다음과 같습니다:

  • 날짜를 사용자 정의 표시 형식으로 표시
  • 소수 값을 백분율로 표시하고 % 기호를 붙임
  • 불리언 값을 Yes 또는 No로 표시

valueGetter()와 달리 이 함수는 렌더링에만 영향을 미치며—필터링이나 정렬 같은 내부 계산에는 영향을 주지 않습니다.

자세한 내용은 Column 정의—value formatter를 참고하세요.

레시피

긴 텍스트 셀

Data Grid 셀의 긴 텍스트를 팝업으로 표시하려면 셀에 확장 버튼을 보여주도록 커스터마이즈하세요. 클릭하면 셀 크기 증가 없이 텍스트 내용 전체를 보여주는 Popper가 나타납니다.

아래 예시에서 Bio 열의 셀에 마우스를 올리고 확장 버튼을 클릭하면 전체 내용을 볼 수 있습니다.

import * as React from 'react';
import Box from '@mui/material/Box';
import {
  DataGrid,
  GridColDef,
  GridRenderCellParams,
  GridRowModel,
  useGridApiContext,
} from '@mui/x-data-grid';
import { randomInt, randomArrayItem } from '@mui/x-data-grid-generator';
import Popper from '@mui/material/Popper';
import Paper from '@mui/material/Paper';
import IconButton from '@mui/material/IconButton';
import OpenInFullIcon from '@mui/icons-material/OpenInFull';
import ClickAwayListener from '@mui/material/ClickAwayListener';

function ExpandableCell(params: GridRenderCellParams<any, string>) {
  const { id, field, value = '', colDef } = params;
  const [hovered, setHovered] = React.useState(false);
  const [popupOpen, setPopupOpen] = React.useState(false);
  const cellRef = React.useRef<HTMLDivElement>(null);
  const apiRef = useGridApiContext();

  React.useEffect(() => {
    return apiRef.current.subscribeEvent('renderedRowsIntervalChange', (context) => {
      const rowIndex = apiRef.current.getRowIndexRelativeToVisibleRows(id);
      if (rowIndex < context.firstRowIndex || rowIndex >= context.lastRowIndex) {
        setPopupOpen(false);
        setHovered(false);
      }
    });
  }, [apiRef, id]);

  const handleIconClick = () => {
    setPopupOpen(true);
  };

  const handleClose = () => {
    setPopupOpen(false);
    setHovered(false);
  };

  const handleDoubleClick = () => {
    setPopupOpen(false);
    setHovered(false);
    apiRef.current.startCellEditMode({ id, field });
  };

  return (
    <React.Fragment>
      <Box
        sx={{
          overflow: 'hidden',
          textOverflow: 'ellipsis',
          whiteSpace: 'nowrap',
        }}
      >
        {value}
      </Box>
      <ClickAwayListener onClickAway={handleClose}>
        <Box
          ref={cellRef}
          onMouseEnter={() => setHovered(true)}
          onMouseLeave={() => !popupOpen && setHovered(false)}
          sx={{
            inset: 0,
            position: 'absolute',
            '.MuiDataGrid-cell:has(&)': {
              position: 'relative',
              overflow: 'unset',
            },
          }}
        >
          {hovered && !popupOpen && (
            <IconButton
              size="small"
              onClick={handleIconClick}
              sx={{
                position: 'absolute',
                bottom: 0,
                right: 0,
                p: '2px',
                bgcolor: 'background.paper',
                border: '1px solid',
                borderColor: 'divider',
                borderRadius: 0,
                '&:hover': {
                  bgcolor: 'background.paper',
                  color: 'text.primary',
                },
              }}
            >
              <OpenInFullIcon sx={{ fontSize: '0.875rem' }} />
            </IconButton>
          )}
          <Popper
            open={popupOpen}
            anchorEl={cellRef.current}
            placement="bottom-start"
            sx={{ zIndex: 1300 }}
            modifiers={[
              {
                name: 'offset',
                options: { offset: [0, -(cellRef.current?.offsetHeight ?? 0)] },
              },
            ]}
          >
            <Paper
              elevation={4}
              onDoubleClick={handleDoubleClick}
              sx={{
                p: 1,
                boxSizing: 'border-box',
                width: colDef.computedWidth * 1.25,
                maxWidth: '100%',
                minHeight: cellRef.current?.offsetHeight,
                typography: 'body2',
              }}
            >
              {value}
            </Paper>
          </Popper>
        </Box>
      </ClickAwayListener>
    </React.Fragment>
  );
}

const lines = [
  'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
  'Aliquam dapibus, lorem vel mattis aliquet, purus lorem tincidunt mauris, in blandit quam risus sed ipsum.',
  'Maecenas non felis venenatis, porta velit quis, consectetur elit.',
  'Vestibulum commodo et odio a laoreet.',
  'Nullam cursus tincidunt auctor.',
  'Sed feugiat venenatis nulla, sit amet dictum nulla convallis sit amet.',
  'Nulla venenatis justo non felis vulputate, eu mollis metus ornare.',
  'Nam ullamcorper ligula id consectetur auctor.',
  'Phasellus et ultrices dui.',
  'Fusce facilisis egestas massa, et eleifend magna imperdiet et.',
  'Pellentesque ac metus velit.',
  'Vestibulum in massa nibh.',
  'Vestibulum pulvinar aliquam turpis, ac faucibus risus varius a.',
];

const columns: GridColDef[] = [
  { field: 'id', headerName: 'ID' },
  {
    field: 'bio',
    headerName: 'Bio',
    width: 400,
    renderCell: (params) => <ExpandableCell {...params} />,
  },
];

const rows: GridRowModel[] = [];

for (let i = 0; i < 50; i += 1) {
  const bio = [];

  for (let j = 0; j < randomInt(1, 7); j += 1) {
    bio.push(randomArrayItem(lines));
  }

  rows.push({
    id: i,
    bio: bio.join(' '),
  });
}

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

:::info 이 레시피는 긴 텍스트 편집을 지원하도록 확장할 수 있습니다. 자세한 내용은 Editing recipes—Multiline editing을 참고하세요. :::

더 알아보기 (Learn more)