Data Grid - 편집
Data Grid - 편집 (Editing)
Data Grid는 셀 및 행 편집을 내장 지원합니다.
본문
완전한 기능의 CRUD (Full-featured CRUD)
Data Grid는 단순한 데이터 시각화 도구가 아닙니다. 데이터셋을 관리할 수 있는 내장 편집 기능을 제공합니다. 아래 데모는 엔터프라이즈 애플리케이션에서 흔히 볼 수 있는 완전한 기능의 CRUD(Create, Read, Update, Delete)를 보여 줍니다.
:::info 편집 API의 자세한 내용은 다음 섹션들에서 확인할 수 있습니다. :::
import * as React from 'react';
import Box from '@mui/material/Box';
import Tooltip from '@mui/material/Tooltip';
import AddIcon from '@mui/icons-material/Add';
import EditIcon from '@mui/icons-material/Edit';
import DeleteIcon from '@mui/icons-material/DeleteOutlined';
import SaveIcon from '@mui/icons-material/Save';
import CancelIcon from '@mui/icons-material/Close';
import {
GridRowsProp,
GridRowModesModel,
GridRowModes,
DataGrid,
GridColDef,
GridEventListener,
GridRowId,
GridRowModel,
GridRowEditStopReasons,
GridSlotProps,
Toolbar,
ToolbarButton,
GridSlots,
gridEditRowsStateSelector,
useGridSelector,
useGridApiContext,
GridActionsCell,
GridRenderCellParams,
GridActionsCellItem,
} from '@mui/x-data-grid';
import {
randomCreatedDate,
randomTraderName,
randomId,
randomArrayItem,
} from '@mui/x-data-grid-generator';
const roles = ['Market', 'Finance', 'Development'];
const randomRole = () => {
return randomArrayItem(roles);
};
const initialRows: GridRowsProp = [
{
id: randomId(),
name: randomTraderName(),
age: 25,
joinDate: randomCreatedDate(),
role: randomRole(),
bio: 'A passionate developer with 5 years of experience in building scalable web applications.',
},
{
id: randomId(),
name: randomTraderName(),
age: 36,
joinDate: randomCreatedDate(),
role: randomRole(),
bio: 'Senior analyst specializing in market trends and financial forecasting.',
},
{
id: randomId(),
name: randomTraderName(),
age: 19,
joinDate: randomCreatedDate(),
role: randomRole(),
bio: 'Junior team member eager to learn and contribute to innovative projects.',
},
{
id: randomId(),
name: randomTraderName(),
age: 28,
joinDate: randomCreatedDate(),
role: randomRole(),
bio: 'Project manager with expertise in agile methodologies and team leadership.',
},
{
id: randomId(),
name: randomTraderName(),
age: 23,
joinDate: randomCreatedDate(),
role: randomRole(),
bio: 'Creative designer focused on user experience and interface design.',
},
];
declare module '@mui/x-data-grid' {
interface ToolbarPropsOverrides {
setRows: (newRows: (oldRows: GridRowsProp) => GridRowsProp) => void;
setRowModesModel: (
newModel: (oldModel: GridRowModesModel) => GridRowModesModel,
) => void;
}
}
function EditToolbar(props: GridSlotProps['toolbar']) {
const { setRows, setRowModesModel } = props;
const handleClick = () => {
const id = randomId();
setRows((oldRows) => [
...oldRows,
{ id, name: '', age: '', role: '', bio: '', isNew: true },
]);
setRowModesModel((oldModel) => ({
...oldModel,
[id]: { mode: GridRowModes.Edit, fieldToFocus: 'name' },
}));
};
return (
<Toolbar>
<Tooltip title="Add record">
<ToolbarButton onClick={handleClick}>
<AddIcon fontSize="small" />
</ToolbarButton>
</Tooltip>
</Toolbar>
);
}
interface ActionHandlers {
handleCancelClick: (id: GridRowId) => void;
handleDeleteClick: (id: GridRowId) => void;
handleEditClick: (id: GridRowId) => void;
handleSaveClick: (id: GridRowId) => void;
}
const ActionHandlersContext = React.createContext<ActionHandlers>({
handleCancelClick: () => {},
handleDeleteClick: () => {},
handleEditClick: () => {},
handleSaveClick: () => {},
});
function ActionsCell(props: GridRenderCellParams) {
const apiRef = useGridApiContext();
const rowModesModel = useGridSelector(apiRef, gridEditRowsStateSelector);
const isInEditMode = typeof rowModesModel[props.id] !== 'undefined';
const { handleSaveClick, handleCancelClick, handleEditClick, handleDeleteClick } =
React.useContext(ActionHandlersContext);
return (
<GridActionsCell {...props}>
{isInEditMode ? (
<React.Fragment>
<GridActionsCellItem
icon={<SaveIcon />}
label="Save"
material={{ sx: { color: 'primary.main' } }}
onClick={() => handleSaveClick(props.id)}
/>
<GridActionsCellItem
icon={<CancelIcon />}
label="Cancel"
className="textPrimary"
onClick={() => handleCancelClick(props.id)}
color="inherit"
/>
</React.Fragment>
) : (
<React.Fragment>
<GridActionsCellItem
icon={<EditIcon />}
label="Edit"
className="textPrimary"
onClick={() => handleEditClick(props.id)}
color="inherit"
/>
<GridActionsCellItem
icon={<DeleteIcon />}
label="Delete"
onClick={() => handleDeleteClick(props.id)}
color="inherit"
/>
</React.Fragment>
)}
</GridActionsCell>
);
}
const columns: GridColDef[] = [
{ field: 'name', headerName: 'Name', width: 180, editable: true, rowHeader: true },
{
field: 'bio',
headerName: 'Bio',
type: 'longText',
width: 200,
editable: true,
},
{
field: 'age',
headerName: 'Age',
type: 'number',
width: 80,
align: 'left',
headerAlign: 'left',
editable: true,
},
{
field: 'joinDate',
headerName: 'Join date',
type: 'date',
width: 180,
editable: true,
},
{
field: 'role',
headerName: 'Department',
width: 220,
editable: true,
type: 'singleSelect',
valueOptions: ['Market', 'Finance', 'Development'],
},
{
field: 'actions',
type: 'actions',
headerName: 'Actions',
width: 100,
cellClassName: 'actions',
renderCell: (params) => <ActionsCell {...params} />,
},
];
export default function FullFeaturedCrudGrid() {
const [rows, setRows] = React.useState(initialRows);
const [rowModesModel, setRowModesModel] = React.useState<GridRowModesModel>({});
const handleRowEditStop: GridEventListener<'rowEditStop'> = (params, event) => {
if (params.reason === GridRowEditStopReasons.rowFocusOut) {
event.defaultMuiPrevented = true;
}
};
const actionHandlers = React.useMemo<ActionHandlers>(
() => ({
handleEditClick: (id: GridRowId) => {
setRowModesModel((prevRowModesModel) => ({
...prevRowModesModel,
[id]: { mode: GridRowModes.Edit },
}));
},
handleSaveClick: (id: GridRowId) => {
setRowModesModel((prevRowModesModel) => ({
...prevRowModesModel,
[id]: { mode: GridRowModes.View },
}));
},
handleDeleteClick: (id: GridRowId) => {
setRows((prevRows) => prevRows.filter((row) => row.id !== id));
},
handleCancelClick: (id: GridRowId) => {
setRowModesModel((prevRowModesModel) => {
return {
...prevRowModesModel,
[id]: { mode: GridRowModes.View, ignoreModifications: true },
};
});
setRows((prevRows) => {
const editedRow = prevRows.find((row) => row.id === id);
if (editedRow!.isNew) {
return prevRows.filter((row) => row.id !== id);
}
return prevRows;
});
},
}),
[],
);
const processRowUpdate = (newRow: GridRowModel) => {
const updatedRow = { ...newRow, isNew: false };
setRows((prevRows) =>
prevRows.map((row) => (row.id === newRow.id ? updatedRow : row)),
);
return updatedRow;
};
return (
<Box
sx={{
height: 500,
width: '100%',
'& .actions': {
color: 'text.secondary',
},
'& .textPrimary': {
color: 'text.primary',
},
}}
>
<ActionHandlersContext.Provider value={actionHandlers}>
<DataGrid
rows={rows}
columns={columns}
editMode="row"
rowModesModel={rowModesModel}
onRowModesModelChange={setRowModesModel}
onRowEditStop={handleRowEditStop}
processRowUpdate={processRowUpdate}
showToolbar
slots={{ toolbar: EditToolbar as GridSlots['toolbar'] }}
slotProps={{
toolbar: { setRows, setRowModesModel },
}}
/>
</ActionHandlersContext.Provider>
</Box>
);
}
열을 편집 가능하게 만들기 (Making a column editable)
열의 column 정의에서 editable 속성을 활성화하면 해당 열을 편집 가능하게 만들 수 있습니다.
이렇게 하면 사용자가 지정된 열의 모든 셀을 편집할 수 있습니다.
예를 들어 아래 코드 조각에서 사용자는 name 열의 셀은 편집할 수 있지만 id 열의 셀은 편집할 수 없습니다.
<DataGrid columns={[{ field: 'id' }, { field: 'name', editable: true }]} />
아래 데모는 모든 열을 편집 가능하게 만드는 예를 보여 줍니다. 아무 셀이나 더블클릭하거나 Enter를 눌러 직접 사용해 보세요.
import { DataGrid, GridColDef, GridRowsProp } from '@mui/x-data-grid';
import {
randomCreatedDate,
randomTraderName,
randomUpdatedDate,
} from '@mui/x-data-grid-generator';
export default function BasicEditingGrid() {
return (
<div style={{ height: 300, width: '100%' }}>
<DataGrid rows={rows} columns={columns} />
</div>
);
}
const columns: GridColDef[] = [
{ field: 'name', headerName: 'Name', width: 180, editable: true, rowHeader: true },
{
field: 'bio',
headerName: 'Bio',
type: 'longText',
width: 200,
editable: true,
},
{
field: 'age',
headerName: 'Age',
type: 'number',
editable: true,
align: 'left',
headerAlign: 'left',
},
{
field: 'dateCreated',
headerName: 'Date Created',
type: 'date',
width: 180,
editable: true,
},
{
field: 'lastLogin',
headerName: 'Last Login',
type: 'dateTime',
width: 220,
editable: true,
},
];
const rows: GridRowsProp = [
{
id: 1,
name: randomTraderName(),
age: 25,
bio: 'A passionate developer with 5 years of experience in building scalable web applications.',
dateCreated: randomCreatedDate(),
lastLogin: randomUpdatedDate(),
},
{
id: 2,
name: randomTraderName(),
age: 36,
bio: 'Senior analyst specializing in market trends and financial forecasting.',
dateCreated: randomCreatedDate(),
lastLogin: randomUpdatedDate(),
},
{
id: 3,
name: randomTraderName(),
age: 19,
bio: 'Junior team member eager to learn and contribute to innovative projects.',
dateCreated: randomCreatedDate(),
lastLogin: randomUpdatedDate(),
},
{
id: 4,
name: randomTraderName(),
age: 28,
bio: 'Project manager with expertise in agile methodologies and team leadership.',
dateCreated: randomCreatedDate(),
lastLogin: randomUpdatedDate(),
},
{
id: 5,
name: randomTraderName(),
age: 23,
bio: 'Creative designer focused on user experience and interface design.',
dateCreated: randomCreatedDate(),
lastLogin: randomUpdatedDate(),
},
];
행 편집 (Row editing)
기본적으로 한 번에 한 셀만 편집할 수 있습니다. 하지만 사용자가 행의 모든 셀을 동시에 편집하도록 할 수 있습니다.
이 동작을 활성화하려면 Data Grid의 editMode prop을 "row"로 설정하세요. 각 열 정의에서도 editable 속성을 설정해 어떤 열이 편집 가능한지 지정해야 합니다. 셀 편집에 적용되는 기본 규칙이 행 편집에도 동일하게 적용됩니다.
<DataGrid editMode="row" columns={[{ field: 'name', editable: true }]} />
아래 데모는 행 편집이 어떻게 동작하는지 보여 줍니다. 사용자는 셀 편집에서 제공되는 것과 동일한 동작으로(예: 셀 더블클릭) 행 편집을 시작하고 중지할 수 있습니다.
import { DataGrid, GridColDef, GridRowsProp } from '@mui/x-data-grid';
import {
randomCreatedDate,
randomTraderName,
randomUpdatedDate,
} from '@mui/x-data-grid-generator';
export default function BasicRowEditingGrid() {
return (
<div style={{ height: 300, width: '100%' }}>
<DataGrid editMode="row" rows={rows} columns={columns} />
</div>
);
}
const columns: GridColDef[] = [
{ field: 'name', headerName: 'Name', width: 180, editable: true, rowHeader: true },
{
field: 'bio',
headerName: 'Bio',
type: 'longText',
width: 200,
editable: true,
},
{
field: 'age',
headerName: 'Age',
type: 'number',
editable: true,
align: 'left',
headerAlign: 'left',
},
{
field: 'dateCreated',
headerName: 'Date Created',
type: 'date',
width: 180,
editable: true,
},
{
field: 'lastLogin',
headerName: 'Last Login',
type: 'dateTime',
width: 220,
editable: true,
},
];
const rows: GridRowsProp = [
{
id: 1,
name: randomTraderName(),
age: 25,
bio: 'A passionate developer with 5 years of experience in building scalable web applications.',
dateCreated: randomCreatedDate(),
lastLogin: randomUpdatedDate(),
},
{
id: 2,
name: randomTraderName(),
age: 36,
bio: 'Senior analyst specializing in market trends and financial forecasting.',
dateCreated: randomCreatedDate(),
lastLogin: randomUpdatedDate(),
},
{
id: 3,
name: randomTraderName(),
age: 19,
bio: 'Junior team member eager to learn and contribute to innovative projects.',
dateCreated: randomCreatedDate(),
lastLogin: randomUpdatedDate(),
},
{
id: 4,
name: randomTraderName(),
age: 28,
bio: 'Project manager with expertise in agile methodologies and team leadership.',
dateCreated: randomCreatedDate(),
lastLogin: randomUpdatedDate(),
},
{
id: 5,
name: randomTraderName(),
age: 23,
bio: 'Creative designer focused on user experience and interface design.',
dateCreated: randomCreatedDate(),
lastLogin: randomUpdatedDate(),
},
];
:::warning
설계상 셀의 값을 변경하면 다른 열의 모든 preProcessEditCellProps 콜백도 호출됩니다.
이를 통해 한 셀의 값이 같은 행의 다른 셀의 유효성 검사 상태에 영향을 주는 조건부 유효성 검사를 적용할 수 있습니다.
값이 변경되었을 때만 유효성 검사를 실행하려면 hasChanged 매개변수가 true인지 확인하세요.
preProcessEditCellProps 사용에 대한 자세한 내용은 편집 유효성 검사 섹션을 참고하세요.
:::
편집 모드와 보기 모드 전환 (Switching between edit and view modes)
각 셀과 행에는 edit와 view 두 가지 모드가 있습니다. edit 모드에서는 사용자가 셀 또는 행의 콘텐츠를 직접 변경할 수 있습니다.
편집 시작 (Start editing)
셀이 view 모드일 때 사용자는 다음 동작 중 하나로 셀(editMode="row"이면 행) 편집을 시작할 수 있습니다:
-
셀 더블클릭
-
Enter, Backspace, Delete 누르기—뒤의 두 옵션은 모두 기존 콘텐츠를 삭제합니다
-
a, E, 0, $ 같은 출력 가능한 키 누르기
-
편집할 셀의 행 ID와 열 필드를 전달해
apiRef.current.startCellEditMode호출apiRef.current.startCellEditMode({ id: 1, field: 'name' }); -
행의 ID를 전달해
apiRef.current.startRowEditMode호출(editMode="row"일 때만 사용 가능).apiRef.current.startRowEditMode({ id: 1 });
:::info 이 레시피를 따라 단일 클릭으로도 편집 모드에 들어갈 수 있습니다. :::
편집 중지 (Stop editing)
셀이 edit 모드일 때 사용자는 다음 상호작용 중 하나로 편집을 중지할 수 있습니다:
-
Escape 누르기—변경 사항도 되돌립니다
-
Tab 누르기—변경 사항도 저장합니다
-
Enter 누르기—변경 사항도 저장하고 같은 열의 다음 셀로 포커스를 이동합니다
-
셀 또는 행 바깥 클릭—변경 사항도 저장합니다
-
편집된 셀의 행 ID와 열 필드를 전달해
apiRef.current.stopCellEditMode({ id, field })호출apiRef.current.stopCellEditMode({ id: 1, field: 'name' }); // or apiRef.current.stopCellEditMode({ id: 1, field: 'name', ignoreModifications: true, // will also discard the changes made }); -
행의 ID를 전달해
apiRef.current.stopRowEditMode호출(editMode="row"일 때만 가능).apiRef.current.stopRowEditMode({ id: 1 }); // or apiRef.current.stopRowEditMode({ id: 1, ignoreModifications: true, // will also discard the changes made });
행 내 특정 셀 편집 비활성화 (Disable editing of specific cells within a row)
editable 속성은 열 수준에서 어떤 셀이 편집 가능한지 제어합니다.
isCellEditable 콜백 prop을 사용해 주어진 행에서 사용자가 편집할 수 있는 개별 셀을 정의할 수 있습니다.
이 콜백은 GridCellParams 객체와 함께 호출되며, 셀이 편집 가능하면 true, 그렇지 않으면 false를 반환해야 합니다.
다음 데모에서는 Age 값이 짝수인 행만 편집 가능합니다.
편집 가능한 셀은 가시성을 높이기 위해 초록색 배경을 가집니다.
import Box from '@mui/material/Box';
import { DataGrid, GridColDef, GridRowsProp } from '@mui/x-data-grid';
import {
randomCreatedDate,
randomTraderName,
randomUpdatedDate,
} from '@mui/x-data-grid-generator';
export default function IsCellEditableGrid() {
return (
<Box
sx={(theme) => ({
height: 400,
width: '100%',
'& .MuiDataGrid-cell--editable': {
bgcolor: 'rgb(217 243 190)',
...theme.applyStyles('dark', {
bgcolor: '#376331',
}),
},
})}
>
<DataGrid
rows={rows}
columns={columns}
isCellEditable={(params) => params.row.age % 2 === 0}
/>
</Box>
);
}
const columns: GridColDef[] = [
{ field: 'name', headerName: 'Name', width: 180, editable: true, rowHeader: true },
{
field: 'age',
headerName: 'Age',
type: 'number',
editable: true,
align: 'left',
headerAlign: 'left',
},
{
field: 'dateCreated',
headerName: 'Date Created',
type: 'date',
width: 180,
editable: true,
},
{
field: 'lastLogin',
headerName: 'Last Login',
type: 'dateTime',
width: 220,
editable: true,
},
];
const rows: GridRowsProp = [
{
id: 1,
name: randomTraderName(),
age: 25,
dateCreated: randomCreatedDate(),
lastLogin: randomUpdatedDate(),
},
{
id: 2,
name: randomTraderName(),
age: 36,
dateCreated: randomCreatedDate(),
lastLogin: randomUpdatedDate(),
},
{
id: 3,
name: randomTraderName(),
age: 19,
dateCreated: randomCreatedDate(),
lastLogin: randomUpdatedDate(),
},
{
id: 4,
name: randomTraderName(),
age: 28,
dateCreated: randomCreatedDate(),
lastLogin: randomUpdatedDate(),
},
{
id: 5,
name: randomTraderName(),
age: 23,
dateCreated: randomCreatedDate(),
lastLogin: randomUpdatedDate(),
},
];
값 파서와 값 세터 (Value parser and value setter)
열 정의에서 valueParser 속성을 사용해 사용자가 입력한 값을 수정할 수 있습니다—예를 들어 값을 다른 형식으로 변환:
const columns: GridColDef[] = [
{
valueParser: (value, row, column, apiRef) => {
return value.toLowerCase();
},
},
];
열 정의의 valueSetter 속성을 사용해 새 값으로 행이 업데이트되는 방식을 사용자 지정할 수 있습니다.
이를 통해 중첩 객체에서 값을 삽입할 수 있습니다.
이 콜백은 저장할 새 셀 값과 그 셀이 속한 행을 포함한 객체와 함께 호출됩니다.
이미 valueGetter를 사용해 중첩 객체에서 값을 추출하고 있다면 valueSetter도 필요할 가능성이 높습니다.
const columns: GridColDef[] = [
{
valueSetter: (value, row) => {
const [firstName, lastName] = value!.toString().split(' ');
return { ...row, firstName, lastName };
},
},
];
다음 데모에서는 Full name 열에 valueParser와 valueSetter가 모두 정의되어 있습니다.
valueParser는 입력된 값을 대문자화하고, valueSetter는 값을 분리해 행 모델에 올바르게 저장합니다:
import {
DataGrid,
GridColDef,
GridValueGetter,
GridValueSetter,
GridValueParser,
} from '@mui/x-data-grid';
type Row = (typeof defaultRows)[number];
const setFullName: GridValueSetter<Row> = (value, row) => {
const [firstName, lastName] = value!.toString().split(' ');
return { ...row, firstName, lastName };
};
const parseFullName: GridValueParser = (value) => {
return String(value)
.split(' ')
.map((str) => (str.length > 0 ? str[0].toUpperCase() + str.slice(1) : ''))
.join(' ');
};
export default function ValueParserSetterGrid() {
return (
<div style={{ height: 400, width: '100%' }}>
<DataGrid rows={defaultRows} columns={columns} />
</div>
);
}
const defaultRows = [
{ 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<Row> = (value, row) => {
return `${row.firstName || ''} ${row.lastName || ''}`;
};
const columns: GridColDef[] = [
{ field: 'firstName', headerName: 'First name', width: 130, editable: true },
{ field: 'lastName', headerName: 'Last name', width: 130, editable: true },
{
field: 'fullName',
headerName: 'Full name',
rowHeader: true,
width: 160,
editable: true,
valueGetter: getFullName,
valueSetter: setFullName,
valueParser: parseFullName,
sortComparator: (v1, v2) => v1!.toString().localeCompare(v2!.toString()),
},
];
유효성 검사 (Validation)
열 정의가 preProcessEditCellProps 속성에 콜백을 설정하면 이 열의 셀에 새 값이 입력될 때마다 호출됩니다.
이 속성은 편집 컴포넌트에 전달되는 props를 사전 처리할 수 있게 해 줍니다.
preProcessEditCellProps 콜백은 다음 속성을 포함한 객체와 함께 호출됩니다:
id: 행 IDrow: 편집 모드에 들어가기 전 셀 또는 행의 값을 담은 행 모델props: 값 파서를 거친 값이 담긴, 편집 컴포넌트에 전달되는 propshasChanged:props.value가 이 콜백이 마지막으로 호출된 때와 다른지 결정
데이터 유효성 검사는 이렇게 할 수 있는 사전 처리의 한 유형입니다.
입력된 데이터를 검증하려면 props.value가 유효한지 확인하는 콜백을 preProcessEditCellProps에 전달하세요.
새 값이 유효하지 않으면 아래 예시처럼 props.error를 truthy 값으로 설정하고 수정된 props를 반환하세요.
사용자가 업데이트된 값을 저장하려 할 때 error 속성이 truthy(유효하지 않음)이면 변경이 거부됩니다.
const columns: GridColDef[] = [
{
field: 'firstName',
preProcessEditCellProps: (params: GridPreProcessEditCellProps) => {
const hasError = params.props.value.length < 3;
return { ...params.props, error: hasError };
},
},
];
:::warning
콜백 안에서 props.value를 변경해도 효과가 없습니다. 사전 처리하려면 값 파서를 사용하세요.
:::
아래 데모는 서버 측 데이터 유효성 검사의 예를 포함합니다.
이 경우 콜백은 수정된 props로 resolve되는 promise를 반환합니다.
props.error에 전달된 값은 error prop으로 편집 컴포넌트에 직접 전달됩니다.
promise가 resolve되지 않는 동안 편집 컴포넌트는 값이 true인 isProcessingProps prop을 받습니다.
import * as React from 'react';
import { styled } from '@mui/material/styles';
import Tooltip, { tooltipClasses, TooltipProps } from '@mui/material/Tooltip';
import {
GridColDef,
GridRowsProp,
DataGrid,
GridPreProcessEditCellProps,
GridEditInputCell,
GridRenderEditCellParams,
} from '@mui/x-data-grid';
const StyledBox = styled('div')(({ theme }) => ({
height: 400,
width: '100%',
'& .MuiDataGrid-cell--editable': {
backgroundColor: 'rgb(217 243 190)',
'& .MuiInputBase-root': {
height: '100%',
},
...theme.applyStyles('dark', {
backgroundColor: '#376331',
}),
},
'& .Mui-error': {
backgroundColor: 'rgb(126,10,15, 0.1)',
color: '#750f0f',
...theme.applyStyles('dark', {
backgroundColor: 'rgb(126,10,15, 0)',
color: '#ff4343',
}),
},
}));
let promiseTimeout: ReturnType<typeof setTimeout>;
function validateName(username: string): Promise<boolean> {
const existingUsers = rows.map((row) => row.name.toLowerCase());
return new Promise<any>((resolve) => {
promiseTimeout = setTimeout(
() => {
const exists = existingUsers.includes(username.toLowerCase());
resolve(exists ? `${username} is already taken.` : null);
},
// eslint-disable-next-line no-restricted-properties -- simulates network latency
Math.random() * 500 + 100,
);
});
}
const StyledTooltip = styled(({ className, ...props }: TooltipProps) => (
<Tooltip {...props} classes={{ popper: className }} />
))(({ theme }) => ({
[`& .${tooltipClasses.tooltip}`]: {
backgroundColor: theme.palette.error.main,
color: theme.palette.error.contrastText,
},
}));
function NameEditInputCell(props: GridRenderEditCellParams) {
const { error } = props;
return (
<StyledTooltip open={!!error} title={error}>
<GridEditInputCell {...props} />
</StyledTooltip>
);
}
function renderEditName(params: GridRenderEditCellParams) {
return <NameEditInputCell {...params} />;
}
export default function ValidateServerNameGrid() {
const preProcessEditCellProps = async (params: GridPreProcessEditCellProps) => {
const errorMessage = await validateName(params.props.value!.toString());
return { ...params.props, error: errorMessage };
};
const columns: GridColDef[] = [
{
field: 'name',
headerName: 'MUI Contributor',
rowHeader: true,
width: 180,
editable: true,
preProcessEditCellProps,
renderEditCell: renderEditName,
},
];
React.useEffect(() => {
return () => {
clearTimeout(promiseTimeout);
};
}, []);
return (
<StyledBox>
<DataGrid
rows={rows}
columns={columns}
isCellEditable={(params) => params.row.id === 5}
/>
</StyledBox>
);
}
const rows: GridRowsProp = [
{
id: 1,
name: 'Damien',
},
{
id: 2,
name: 'Olivier',
},
{
id: 3,
name: 'Danail',
},
{
id: 4,
name: 'Matheus',
},
{
id: 5,
name: 'You?',
},
];
제어 모델 (Controlled model)
cellModesModel과 rowModesModel props(editMode="row"일 때만 동작)를 사용해 활성 모드를 제어할 수 있습니다.
cellModesModel prop은 다음 예시처럼 주어진 행의 특정 열 필드에 대한 mode(및 추가 옵션)를 포함한 객체를 받습니다.
허용되는 옵션은 apiRef.current.startCellEditMode()와 apiRef.current.stopCellEditMode()에서 사용 가능한 것과 동일합니다.
// Changes the mode of field=name from row with id=1 to "edit"
<DataGrid
cellModesModel={{ 1: { name: { mode: GridCellModes.Edit } } }}
/>
// Changes the mode of field=name from row with id=1 to "view", ignoring modifications made
<DataGrid
cellModesModel={{ 1: { name: { mode: GridCellModes.View, ignoreModifications: true } } }}
/>
행 편집의 경우 rowModesModel props도 유사하게 동작합니다.
허용되는 옵션은 apiRef.current.startRowEditMode()와 apiRef.current.stopRowEditMode()에서 사용 가능한 것과 동일합니다.
// Changes the mode of the row with id=1 to "edit"
<DataGrid
editMode="row"
rowModesModel={{ 1: { mode: GridRowModes.Edit } }}
/>
// Changes the mode of the row with id=1 to "view", ignoring modifications made
<DataGrid
editMode="row"
rowModesModel={{ 1: { mode: GridRowModes.View, ignoreModifications: true } }}
/>
또한 onCellModesModelChange()와 onRowModesModelChange() 콜백 props(editMode="row"일 때만 동작)도 사용할 수 있습니다.
이를 사용해 각각의 prop을 업데이트하세요.
아래 데모에서는 외부 버튼으로 선택된 셀의 모드를 제어하기 위해 cellModesModel을 사용합니다.
행 편집을 사용하는 예는 완전한 기능의 CRUD 컴포넌트를 확인하세요.
import * as React from 'react';
import Tooltip from '@mui/material/Tooltip';
import {
GridColDef,
GridRowsProp,
DataGrid,
GridRowId,
GridCellModes,
GridEventListener,
GridCellModesModel,
GridSlotProps,
Toolbar,
ToolbarButton,
} from '@mui/x-data-grid';
import {
randomCreatedDate,
randomTraderName,
randomUpdatedDate,
} from '@mui/x-data-grid-generator';
import SaveIcon from '@mui/icons-material/Save';
import EditIcon from '@mui/icons-material/Edit';
import CancelIcon from '@mui/icons-material/Cancel';
interface SelectedCellParams {
id: GridRowId;
field: string;
}
declare module '@mui/x-data-grid' {
interface ToolbarPropsOverrides {
selectedCellParams: SelectedCellParams | null;
cellModesModel: GridCellModesModel;
setCellModesModel: (value: GridCellModesModel) => void;
cellMode: 'view' | 'edit';
}
}
function EditToolbar(props: GridSlotProps['toolbar']) {
const { selectedCellParams, cellMode, cellModesModel, setCellModesModel } = props;
const handleSaveOrEdit = () => {
if (!selectedCellParams) {
return;
}
const { id, field } = selectedCellParams;
if (cellMode === 'edit') {
setCellModesModel({
...cellModesModel,
[id]: { ...cellModesModel[id], [field]: { mode: GridCellModes.View } },
});
} else {
setCellModesModel({
...cellModesModel,
[id]: { ...cellModesModel[id], [field]: { mode: GridCellModes.Edit } },
});
}
};
const handleCancel = () => {
if (!selectedCellParams) {
return;
}
const { id, field } = selectedCellParams;
setCellModesModel({
...cellModesModel,
[id]: {
...cellModesModel[id],
[field]: { mode: GridCellModes.View, ignoreModifications: true },
},
});
};
const handlePointerDown = (event: React.PointerEvent) => {
// Keep the focus in the cell
event.preventDefault();
};
return (
<Toolbar>
<Tooltip title={cellMode === 'edit' ? 'Save' : 'Edit'}>
<ToolbarButton onClick={handleSaveOrEdit}>
{cellMode === 'edit' ? (
<SaveIcon fontSize="small" />
) : (
<EditIcon fontSize="small" />
)}
</ToolbarButton>
</Tooltip>
{cellMode === 'edit' && (
<Tooltip title="Cancel">
<ToolbarButton onClick={handleCancel} onPointerDown={handlePointerDown}>
<CancelIcon fontSize="small" />
</ToolbarButton>
</Tooltip>
)}
</Toolbar>
);
}
export default function StartEditButtonGrid() {
const [selectedCellParams, setSelectedCellParams] =
React.useState<SelectedCellParams | null>(null);
const [cellModesModel, setCellModesModel] = React.useState<GridCellModesModel>({});
const handleCellFocus = React.useCallback(
(event: React.FocusEvent<HTMLDivElement>) => {
const row = event.currentTarget.parentElement;
const id = row!.dataset.id!;
const field = event.currentTarget.dataset.field!;
setSelectedCellParams({ id, field });
},
[],
);
const cellMode = React.useMemo(() => {
if (!selectedCellParams) {
return 'view';
}
const { id, field } = selectedCellParams;
return cellModesModel[id]?.[field]?.mode || 'view';
}, [cellModesModel, selectedCellParams]);
const handleCellKeyDown = React.useCallback<GridEventListener<'cellKeyDown'>>(
(params, event) => {
if (cellMode === 'edit') {
// Prevents calling event.preventDefault() if Tab is pressed on a cell in edit mode
event.defaultMuiPrevented = true;
}
},
[cellMode],
);
const handleCellEditStop = React.useCallback<GridEventListener<'cellEditStop'>>(
(params, event) => {
event.defaultMuiPrevented = true;
},
[],
);
return (
<div style={{ height: 400, width: '100%' }}>
<DataGrid
rows={rows}
columns={columns}
onCellKeyDown={handleCellKeyDown}
cellModesModel={cellModesModel}
onCellEditStop={handleCellEditStop}
onCellModesModelChange={(model) => setCellModesModel(model)}
slots={{ toolbar: EditToolbar }}
showToolbar
slotProps={{
toolbar: {
cellMode,
selectedCellParams,
cellModesModel,
setCellModesModel,
},
cell: {
onFocus: handleCellFocus,
},
}}
/>
</div>
);
}
const columns: GridColDef[] = [
{ field: 'name', headerName: 'Name', width: 180, editable: true, rowHeader: true },
{
field: 'age',
headerName: 'Age',
type: 'number',
editable: true,
align: 'left',
headerAlign: 'left',
},
{
field: 'dateCreated',
headerName: 'Date Created',
type: 'date',
width: 180,
editable: true,
},
{
field: 'lastLogin',
headerName: 'Last Login',
type: 'dateTime',
width: 220,
editable: true,
},
];
const rows: GridRowsProp = [
{
id: 1,
name: randomTraderName(),
age: 25,
dateCreated: randomCreatedDate(),
lastLogin: randomUpdatedDate(),
},
{
id: 2,
name: randomTraderName(),
age: 36,
dateCreated: randomCreatedDate(),
lastLogin: randomUpdatedDate(),
},
{
id: 3,
name: randomTraderName(),
age: 19,
dateCreated: randomCreatedDate(),
lastLogin: randomUpdatedDate(),
},
{
id: 4,
name: randomTraderName(),
age: 28,
dateCreated: randomCreatedDate(),
lastLogin: randomUpdatedDate(),
},
{
id: 5,
name: randomTraderName(),
age: 23,
dateCreated: randomCreatedDate(),
lastLogin: randomUpdatedDate(),
},
];
:::warning
두 모델 props에 전달된 옵션은 mode가 변경될 때만 적용됩니다.
같은 mode를 유지하면서 셀 또는 행의 매개변수를 업데이트하면 셀이나 행은 같은 모드에 머물게 됩니다.
또한 객체에서 필드나 행 ID를 제거해도 해당 셀이나 행이 "view" 모드로 가지 않습니다.
:::
apiRef
Data Grid는 편집 기능 구현에서 내부적으로 사용되는 일련의 메서드를 apiRef 객체를 통해 노출합니다.
아래 참조는 관련 함수를 설명합니다.
자세한 내용은 API 객체를 참고하세요.
:::warning 이 API는 Data Grid의 내장 props가 특정 사용 사례에 충분하지 않을 때 최후의 수단으로만 사용해야 합니다. :::
import ApiDocs from 'docs/src/modules/components/ApiDocs';
import api from 'docs/pages/x/api/data-grid/grid-editing-api.json';
export default function EditApiNoSnap() {
return <ApiDocs api={api} />;
}