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

Data Grid - 커스텀 편집 컴포넌트

원문 보기 위키 갱신

Data Grid - 커스텀 편집 컴포넌트 (Custom edit component)

커스텀 편집 컴포넌트를 만들어 볼게요.

출처: MUI X documentation

본문

내장된 각 컬럼 타입은 셀의 값을 편집하기 위한 컴포넌트를 제공해요. 컬럼 타입을 커스터마이즈하거나 기존 컴포넌트를 대체하려면 컬럼 정의의 renderEditCell() 속성을 통해 새로운 편집 컴포넌트를 제공할 수 있어요. 이 속성은 셀이 뷰 모드일 때 렌더링되는 renderCell() 속성과 같은 방식으로 동작해요.

function CustomEditComponent(props: GridRenderEditCellParams) {
  return <input type="text" value={params.value} onValueChange={...} />;
}

const columns: GridColDef[] = [
  {
    field: 'firstName',
    renderEditCell: (params: GridRenderEditCellParams) => (
      <CustomEditComponent {...params} />
    ),
  },
];

renderEditCell() 속성은 GridCellParams를 확장한 GridRenderEditCellParams의 모든 params를 전달받아요. 또한 전처리(pre-processing) 과정에서 추가된 props도 params로 전달돼요. 고려해야 할 가장 중요한 params는 다음과 같아요:

  • value: 편집 모드에서 셀의 현재 값을 담고 있으며, GridCellParams의 값을 재정의해요
  • error: 유효성 검사 중 추가된 오류
  • isProcessingProps: preProcessEditCellProps()가 실행 중인지 여부

입력란에 새 값을 입력하면 그 값을 데이터 그리드로 보내야 해요. 이를 위해 행 ID, 컬럼 필드, 새 셀 값을 apiRef.current.setEditCellValue() 호출에 전달하면 돼요. 새 값은 파싱·검증되고, value prop은 다음 렌더링에서 변경 사항을 반영해요.

function CustomEditComponent(props: GridRenderEditCellParams) {
  const { id, value, field } = props;
  const apiRef = useGridApiContext();

  const handleValueChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const newValue = event.target.value; // The new value entered by the user
    apiRef.current.setEditCellValue({ id, field, value: newValue });
  };

  return <input type="text" value={value} onChange={handleValueChange} />;
}

아래 데모는 @mui/material의 Rating 컴포넌트를 기반으로 한 커스텀 편집 컴포넌트를 Rating 컬럼에 구현한 예시예요.

import * as React from 'react';
import Box from '@mui/material/Box';
import Rating from '@mui/material/Rating';
import useEnhancedEffect from '@mui/utils/useEnhancedEffect';
import {
  DataGrid,
  GridRenderCellParams,
  GridColDef,
  useGridApiContext,
} from '@mui/x-data-grid';

function renderRating(params: GridRenderCellParams<any, number>) {
  return <Rating readOnly value={params.value} />;
}

function RatingEditInputCell(props: GridRenderCellParams<any, number>) {
  const { id, value, field, hasFocus } = props;
  const apiRef = useGridApiContext();
  const ref = React.useRef<HTMLElement>(null);

  const handleChange = (event: React.SyntheticEvent, newValue: number | null) => {
    apiRef.current.setEditCellValue({ id, field, value: newValue });
  };

  useEnhancedEffect(() => {
    if (hasFocus && ref.current) {
      const input = ref.current.querySelector<HTMLInputElement>(
        `input[value="${value}"]`,
      );
      input?.focus();
    }
  }, [hasFocus, value]);

  return (
    <Box sx={{ display: 'flex', alignItems: 'center', pr: 2 }}>
      <Rating
        ref={ref}
        name="rating"
        precision={1}
        value={value}
        onChange={handleChange}
      />
    </Box>
  );
}

const renderRatingEditInputCell: GridColDef['renderCell'] = (params) => {
  return <RatingEditInputCell {...params} />;
};

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

const columns: GridColDef[] = [
  {
    field: 'places',
    rowHeader: true,
    headerName: 'Places',
    width: 120,
  },
  {
    field: 'rating',
    headerName: 'Rating',
    display: 'flex',
    renderCell: renderRating,
    renderEditCell: renderRatingEditInputCell,
    editable: true,
    width: 180,
    type: 'number',
  },
];

const rows = [
  { id: 1, places: 'Barcelona', rating: 5 },
  { id: 2, places: 'Rio de Janeiro', rating: 4 },
  { id: 3, places: 'London', rating: 3 },
  { id: 4, places: 'New York', rating: 2 },
];

디바운스 적용 (With debounce)

기본적으로 apiRef.current.setEditCellValue()를 호출할 때마다 새 렌더링이 발생해요. 편집 컴포넌트가 사용자에게 새 값을 입력하도록 요구한다면, 데이터 그리드를 너무 자주 다시 렌더링하면 성능이 크게 저하돼요. 이를 피하는 한 가지 방법은 API 호출을 디바운스하는 거예요. apiRef.current.setEditCellValue()의 debounceMs param을 양의 정수(밀리초 단위)로 설정해 디바운싱을 처리할 수 있어요. API 메서드가 아무리 많이 호출되더라도 해당 시간이 지난 후에만 데이터 그리드가 다시 렌더링돼요.

apiRef.current.setEditCellValue({ id, field, value: newValue, debounceMs: 200 });

데이터 그리드가 주어진 시간이 지난 후에만 다시 렌더링되도록 설정되면, value prop은 매 apiRef.current.setEditCellValue() 호출마다 갱신되지 않아요. UI가 얼어붙는 것을 피하려면, 편집 컴포넌트가 현재 값을 내부 상태로 유지하고 value가 변경될 때 동기화하면 돼요. 이 기능을 활성화하도록 편집 컴포넌트를 수정해 볼게요:

 function CustomEditComponent(props: GridRenderEditCellParams) {
-  const { id, value, field } = props;
+  const { id, value: valueProp, field } = props;
+  const [value, setValue] = React.useState(valueProp);
   const apiRef = useGridApiContext();

   const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
     const newValue = event.target.value; // The new value entered by the user
-    apiRef.current.setEditCellValue({ id, field, value: newValue });
+    apiRef.current.setEditCellValue({ id, field, value: newValue, debounceMs: 200 });
+    setValue(newValue);
   };

+  React.useEffect(() => {
+    setValue(valueProp);
+  }, [valueProp]);
+
   return <input type="text" value={value} onChange={handleChange} />;
 }

자동 종료 (With auto-stop)

편집 컴포넌트가 값이 변경되는 즉시 편집 모드를 종료하면 "자동 종료(auto-stop)" 동작을 가진다고 해요. 일반적인 단계로 만든 콤보 편집 컴포넌트를 상상해 보세요. 기본적으로는 셀의 값을 변경하는 데 두 번의 클릭이 필요해요. 셀 안에서 새 값을 선택하는 첫 번째 클릭과, 셀 밖에서 저장하는 두 번째 클릭이요. 이 두 번째 클릭은 첫 번째 클릭이 편집 모드도 함께 종료한다면 피할 수 있어요. 자동 종료가 있는 편집 컴포넌트를 만들려면 새 값을 설정한 후 apiRef.current.stopCellEditMode()를 호출하면 돼요. apiRef.current.setEditCellValue()는 추가 처리를 수행할 수 있으므로, 편집 모드를 종료하기 전에 이 호출이 완료될 때까지 기다려야 해요. 또한 apiRef.current.setEditCellValue()가 true를 반환했는지 확인하는 것도 좋은 습관이에요. 유효성 검사 과정에서 preProcessEditProps()가 오류를 설정했다면 false를 반환할 거예요.

const handleChange = async (event: SelectChangeEvent) => {
  const isValid = await apiRef.current.setEditCellValue({
    id,
    field,
    value: event.target.value,
  });

  if (isValid) {
    apiRef.current.stopCellEditMode({ id, field });
  }
};

아래 데모는 네이티브 Select 컴포넌트를 기반으로 한 자동 종료 편집 컴포넌트를 Role 컬럼에 구현한 예시예요.

import Select, { SelectChangeEvent } from '@mui/material/Select';
import {
  DataGrid,
  GridRenderCellParams,
  GridColDef,
  useGridApiContext,
} from '@mui/x-data-grid';

function SelectEditInputCell(props: GridRenderCellParams) {
  const { id, value, field } = props;
  const apiRef = useGridApiContext();

  const handleChange = async (event: SelectChangeEvent) => {
    await apiRef.current.setEditCellValue({ id, field, value: event.target.value });
    apiRef.current.stopCellEditMode({ id, field });
  };

  return (
    <Select
      value={value}
      onChange={handleChange}
      size="small"
      sx={{ height: 1 }}
      native
      autoFocus
    >
      <option>Back-end Developer</option>
      <option>Front-end Developer</option>
      <option>UX Designer</option>
    </Select>
  );
}

const renderSelectEditInputCell: GridColDef['renderCell'] = (params) => {
  return <SelectEditInputCell {...params} />;
};

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

const columns = [
  {
    field: 'name',
    headerName: 'Name',
    rowHeader: true,
    width: 120,
  },
  {
    field: 'role',
    headerName: 'Role',
    renderEditCell: renderSelectEditInputCell,
    editable: true,
    width: 180,
  },
];

const rows = [
  {
    id: 1,
    name: 'Olivier',
    role: 'Back-end Developer',
  },
  {
    id: 2,
    name: 'Danail',
    role: 'UX Designer',
  },
  {
    id: 3,
    name: 'Matheus',
    role: 'Front-end Developer',
  },
];

:::warning preProcessEditCellProps()가 오래 걸리는 컬럼에서는 자동 종료 편집 컴포넌트를 사용하지 마세요. apiRef.current.setEditCellValue()를 기다리는 동안 UI가 얼어붙을 수 있어요. 대신 제공되는 상호작용으로 편집 모드를 종료하세요. :::

API

더 알아보기 (Learn more)