Data Grid - 편집 레시피
고급 그리드 커스터마이즈 레시피예요.
본문
여러 줄 편집
다중 줄 텍스트가 있는 열을 만들고 커스텀 편집 컴포넌트를 만들어 편집할 수 있어요.
아래 데모에서 Bio 열은 여러 줄로 구성돼요. 변경을 저장하려면 Ctrl+Enter(macOS에서는 ⌘ Command+Enter)를 사용하세요.
import * as React from 'react';
import {
DataGrid,
GridColDef,
GridRowModel,
GridRenderEditCellParams,
useGridApiContext,
GridColTypeDef,
GridCellEditStopReasons,
} from '@mui/x-data-grid';
import InputBase, { InputBaseProps } from '@mui/material/InputBase';
import Popper from '@mui/material/Popper';
import Paper from '@mui/material/Paper';
import {
randomInt,
randomUserName,
randomArrayItem,
} from '@mui/x-data-grid-generator';
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.',
];
function isKeyboardEvent(event: any): event is React.KeyboardEvent {
return !!event.key;
}
function EditTextarea(props: GridRenderEditCellParams<any, string>) {
const { id, field, value, colDef, hasFocus } = props;
const [valueState, setValueState] = React.useState(value);
const [anchorEl, setAnchorEl] = React.useState<HTMLElement | null>();
const [inputRef, setInputRef] = React.useState<HTMLInputElement | null>(null);
const apiRef = useGridApiContext();
React.useLayoutEffect(() => {
if (hasFocus && inputRef) {
inputRef.focus();
}
}, [hasFocus, inputRef]);
const handleRef = React.useCallback((el: HTMLElement | null) => {
setAnchorEl(el);
}, []);
const handleChange = React.useCallback<NonNullable<InputBaseProps['onChange']>>(
(event) => {
const newValue = event.target.value;
setValueState(newValue);
apiRef.current.setEditCellValue(
{ id, field, value: newValue, debounceMs: 200 },
event,
);
},
[apiRef, field, id],
);
return (
<div style={{ position: 'relative', alignSelf: 'flex-start' }}>
<div
ref={handleRef}
style={{
height: 1,
width: colDef.computedWidth,
display: 'block',
position: 'absolute',
top: 0,
}}
/>
{anchorEl && (
<Popper open anchorEl={anchorEl} placement="bottom-start">
<Paper elevation={1} sx={{ p: 1, minWidth: colDef.computedWidth }}>
<InputBase
multiline
rows={4}
value={valueState}
sx={{ textarea: { resize: 'both' }, width: '100%' }}
onChange={handleChange}
inputRef={(ref) => setInputRef(ref)}
/>
</Paper>
</Popper>
)}
</div>
);
}
const multilineColumn: GridColTypeDef = {
type: 'string',
renderEditCell: (params) => <EditTextarea {...params} />,
};
const columns: GridColDef[] = [
{ field: 'id', headerName: 'ID' },
{ field: 'username', headerName: 'Name', width: 150, rowHeader: true },
{ field: 'age', headerName: 'Age', width: 80, type: 'number' },
{
field: 'bio',
headerName: 'Bio',
width: 400,
editable: true,
...multilineColumn,
},
];
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,
username: randomUserName(),
age: randomInt(10, 80),
bio: bio.join(' '),
});
}
export default function MultilineEditing() {
return (
<div style={{ height: 300, width: '100%' }}>
<DataGrid
rows={rows}
columns={columns}
onCellEditStop={(params, event) => {
if (params.reason !== GridCellEditStopReasons.enterKeyDown) {
return;
}
if (isKeyboardEvent(event) && !event.ctrlKey && !event.metaKey) {
event.defaultMuiPrevented = true;
}
}}
/>
</div>
);
}
자동 완성 편집
옵션이 많은 열의 편집 경험을 개선하려면 Material UI Autocomplete 컴포넌트를 사용해 커스텀 편집 컴포넌트를 만들 수 있어요.
이렇게 하면 키보드 탐색을 유지하면서 입력으로 원하는 값을 검색할 수 있어요.
일관된 편집 환경을 위해 openOnFocus로 Autocomplete를 구성하고 slotProps를 통해 HTML 입력 요소에 autoFocus: true를 설정하세요.
이렇게 하면 사용자가 편집 모드에 들어갈 때 Autocomplete가 자동으로 포커스를 받고 사용 가능한 옵션을 즉시 표시해요.
컴포넌트는 편집 API를 통해 Data Grid의 상태 관리와 통합돼요:
- 사용자가 선택하면
apiRef.current.setEditCellValue()로 셀 값을 업데이트하세요 - 값이 선택된 후
apiRef.current.stopCellEditMode()를 호출해 편집 모드를 종료하세요
import * as React from 'react';
import {
DataGrid,
GridColDef,
GridRenderEditCellParams,
useGridApiContext,
} from '@mui/x-data-grid';
import Autocomplete, { AutocompleteProps } from '@mui/material/Autocomplete';
import Box from '@mui/material/Box';
import TextField from '@mui/material/TextField';
const countries = [
'Argentina',
'Australia',
'Austria',
'Belgium',
'Brazil',
'Canada',
'China',
'Egypt',
'France',
'Germany',
'India',
'Italy',
'Japan',
'Mexico',
'Netherlands',
'New Zealand',
'Poland',
'Portugal',
'Russia',
'South Africa',
'South Korea',
'Spain',
'Switzerland',
'United Kingdom',
'United States',
];
function AutocompleteEditCell(props: GridRenderEditCellParams) {
const { id, field, value, error } = props;
const apiRef = useGridApiContext();
const handleChange: NonNullable<
AutocompleteProps<any, any, any, any>['onChange']
> = React.useCallback(
async (_: React.SyntheticEvent, newValue, reason) => {
await apiRef.current.setEditCellValue({
id,
field,
value: newValue,
});
if (reason !== 'clear') {
// stop editing mode for actions other than clearing the value
apiRef.current.stopCellEditMode({ id, field });
}
},
[id, field, apiRef],
);
return (
<Autocomplete
value={value}
onChange={handleChange}
options={countries}
openOnFocus
fullWidth
onKeyDown={(event) => {
if (event.key === 'Enter') {
// Prevent closing edit mode prematurely
event.stopPropagation();
}
if (event.key === 'Escape') {
apiRef.current.stopCellEditMode({ id, field, ignoreModifications: true });
}
}}
renderInput={(params) => (
<TextField
{...params}
error={error}
slotProps={{
...params.slotProps,
input: {
...params.slotProps.input,
autoFocus: true,
},
}}
/>
)}
sx={{
fontSize: 'inherit',
'& .MuiFormControl-root': {
height: '100%',
},
'& .MuiOutlinedInput-root': {
fontSize: 'inherit',
paddingLeft: '9px',
paddingTop: 0,
paddingBottom: '1px', // to account for the editing cell 1px
},
'& .MuiOutlinedInput-root .MuiAutocomplete-input': {
paddingLeft: 0,
},
'& .MuiOutlinedInput-notchedOutline': {
display: 'none',
},
}}
slotProps={{
listbox: {
sx: {
fontSize: '0.875rem',
},
},
}}
/>
);
}
const rows = [
{ id: 1, country: countries[0] },
{ id: 2, country: countries[1] },
{ id: 3, country: countries[2] },
{ id: 4, country: countries[3] },
{ id: 5, country: countries[4] },
];
const columns: GridColDef[] = [
{
field: 'country',
rowHeader: true,
headerName: 'Country',
width: 200,
editable: true,
renderEditCell: (params) => <AutocompleteEditCell {...params} />,
},
];
export default function AutocompleteEditing() {
return (
<Box sx={{ height: 400, width: '100%' }}>
<DataGrid rows={rows} columns={columns} />
</Box>
);
}
조건부 검증
행의 모든 셀이 편집 모드에 있으면 값을 서로 비교해서 필드를 검증할 수 있어요.
이를 위해 검증 섹션에 설명된 대로 preProcessEditCellProps를 추가하는 것으로 시작하세요.
콜백이 호출되면 같은 행의 다른 필드에서 온 props를 포함하는 추가 otherFieldsProps 매개변수를 받을 거예요.
이 매개변수를 사용해 현재 열의 값이 유효한지 확인하세요.
셀 편집에서처럼 오류를 포함한 수정된 props를 반환하세요.
error 속성이 truthy 값으로 설정된 필드가 하나라도 있으면 행은 편집 모드를 종료하지 않아요.
다음 데모는 Is paid? 열이 체크된 경우에만 Payment method 열에 값을 요구해요:
import { styled } from '@mui/material/styles';
import { DataGrid, GridColDef, GridRowsProp } from '@mui/x-data-grid';
import { randomPrice } from '@mui/x-data-grid-generator';
const StyledBox = styled('div')(({ theme }) => ({
height: 300,
width: '100%',
'& .MuiDataGrid-cell--editing': {
backgroundColor: 'rgb(255,215,115, 0.19)',
color: '#1a3e72',
'& .MuiInputBase-root': {
height: '100%',
},
},
'& .Mui-error': {
backgroundColor: 'rgb(126,10,15, 0.1)',
color: theme.palette.error.main,
...theme.applyStyles('dark', {
backgroundColor: 'rgb(126,10,15, 0)',
}),
},
}));
const rows: GridRowsProp = [
{
id: 1,
expense: 'Light bill',
price: randomPrice(0, 1000),
dueAt: new Date(2021, 6, 8),
isPaid: false,
paymentMethod: '',
},
{
id: 2,
expense: 'Rent',
price: randomPrice(0, 1000),
dueAt: new Date(2021, 7, 1),
isPaid: false,
paymentMethod: '',
},
{
id: 3,
expense: 'Car insurance',
price: randomPrice(0, 1000),
dueAt: new Date(2021, 7, 4),
isPaid: true,
paymentMethod: 'Wire transfer',
},
];
export default function ConditionalValidationGrid() {
const columns: GridColDef[] = [
{
field: 'expense',
headerName: 'Expense',
width: 160,
editable: true,
rowHeader: true,
},
{
field: 'price',
headerName: 'Price',
type: 'number',
width: 120,
editable: true,
},
{
field: 'dueAt',
headerName: 'Due at',
type: 'date',
width: 120,
editable: true,
},
{
field: 'isPaid',
headerName: 'Is paid?',
type: 'boolean',
width: 140,
editable: true,
},
{
field: 'paymentMethod',
headerName: 'Payment method',
type: 'singleSelect',
valueOptions: ['Credit card', 'Wire transfer', 'Cash'],
width: 160,
editable: true,
preProcessEditCellProps: (params) => {
const isPaidProps = params.otherFieldsProps!.isPaid;
const hasError = isPaidProps.value && !params.props.value;
return { ...params.props, error: hasError };
},
},
];
return (
<StyledBox>
<DataGrid rows={rows} columns={columns} editMode="row" />
</StyledBox>
);
}
연결된 필드
한 필드에서 사용 가능한 옵션은 다른 필드의 값에 따라 달라질 수 있어요.
예를 들어 singleSelect 열을 사용한다면 다른 필드에서 선택된 값에 대한 관련 옵션을 반환하는 함수를 valueOptions에 제공할 수 있어요.
const columns: GridColDef[] = [
{
field: 'account',
type: 'singleSelect',
valueOptions: ({ row }) => {
if (!row) {
// The row is not available when filtering this column
return ['Sales', 'Investments', 'Ads', 'Taxes', 'Payroll', 'Utilities'];
}
return row.type === 'Income' // Gets the value of the "type" field
? ['Sales', 'Investments', 'Ads']
: ['Taxes', 'Payroll', 'Utilities'];
},
},
];
위 코드만으로 Type 열에서 선택된 값에 따라 Account 열에 다른 옵션을 표시하기에 충분해요.
남은 유일한 작업은 타입이 바뀌었을 때 account를 초기화하는 거예요.
이전에 선택된 account가 이제 옵션에 존재하지 않기 때문에 이 작업이 필요해요.
이를 해결하려면 내장 컴포넌트를 재사용하는 커스텀 편집 컴포넌트를 만들고 onValueChange prop에 함수를 전달하세요.
이 함수는 apiRef.current.setEditCellValue()를 호출해 다른 필드의 값을 초기화해야 해요.
const CustomTypeEditComponent = (props: GridEditSingleSelectCellProps) => {
const apiRef = useGridApiContext();
const handleValueChange = async () => {
await apiRef.current.setEditCellValue({
id: props.id,
field: 'account',
value: '',
});
};
return <GridEditSingleSelectCell onValueChange={handleValueChange} {...props} />;
};
아래 데모는 위에 보여준 단계들을 결합해요. Type 열의 어떤 셀 값이든 바꿔보면서 실험할 수 있어요. Account 열은 올바른 옵션으로 자동 업데이트돼요.
import Box from '@mui/material/Box';
import {
DataGrid,
GridColDef,
GridRowsProp,
GridEditSingleSelectCell,
GridEditSingleSelectCellProps,
useGridApiContext,
} from '@mui/x-data-grid';
import { randomPrice } from '@mui/x-data-grid-generator';
const rows: GridRowsProp = [
{
id: 1,
description: 'Light bill',
value: randomPrice(0, 1000),
type: 'Expense',
account: 'Utilities',
},
{
id: 3,
description: 'Order #5',
value: randomPrice(0, 1000),
type: 'Income',
account: 'Sales',
},
{
id: 4,
description: 'Google AdSense',
value: randomPrice(0, 1000),
type: 'Income',
account: 'Ads',
},
];
function CustomTypeEditComponent(props: GridEditSingleSelectCellProps) {
const apiRef = useGridApiContext();
const handleValueChange = async () => {
await apiRef.current.setEditCellValue({
id: props.id,
field: 'account',
value: '',
});
};
return <GridEditSingleSelectCell onValueChange={handleValueChange} {...props} />;
}
export default function LinkedFieldsRowEditing() {
const columns: GridColDef[] = [
{
field: 'description',
headerName: 'Description',
width: 160,
editable: true,
rowHeader: true,
},
{
field: 'value',
headerName: 'Value',
type: 'number',
width: 120,
editable: true,
},
{
field: 'type',
headerName: 'Type',
type: 'singleSelect',
valueOptions: ['Income', 'Expense'],
width: 120,
editable: true,
renderEditCell: (params) => <CustomTypeEditComponent {...params} />,
},
{
field: 'account',
headerName: 'Account',
type: 'singleSelect',
valueOptions: ({ row }) => {
if (!row) {
return [
'Sales',
'Investments',
'Ads',
'Taxes',
'Payroll',
'Utilities',
'Marketing',
];
}
return row.type === 'Income'
? ['Sales', 'Investments', 'Ads']
: ['Taxes', 'Payroll', 'Utilities', 'Marketing'];
},
width: 140,
editable: true,
},
];
return (
<Box sx={{ width: '100%', height: 300 }}>
<DataGrid rows={rows} columns={columns} editMode="row" />
</Box>
);
}
:::warning
apiRef.current.setEditCellValue() 호출은 await해야 하는 promise를 반환합니다.
예를 들어 singleSelect 열 타입을 사용하면 await하지 않으면 다른 열이 옵션에 없는 value로 렌더링됩니다.
const handleChange = async () => {
await apiRef.current.setEditCellValue({
id: props.id,
field: 'account',
value: '',
});
};
:::
셀 편집으로도 비슷한 동작을 재현할 수 있어요.
apiRef.current.setEditCellValue() 대신 rows prop을 업데이트하거나 apiRef.current.updateRows()를 사용해야 해요.
사용자가 편집을 취소하는 경우 변경된 셀의 값을 되돌리기 위해 onCellEditStart와 onCellEditStop props도 사용해야 하는 점을 유의하세요.
import * as React from 'react';
import Box from '@mui/material/Box';
import {
DataGrid,
DataGridProps,
GridRowModel,
GridColDef,
GridRowsProp,
GridEditSingleSelectCell,
GridEditSingleSelectCellProps,
GridCellEditStopReasons,
} from '@mui/x-data-grid';
import { randomPrice } from '@mui/x-data-grid-generator';
const initialRows: GridRowsProp = [
{
id: 1,
description: 'Light bill',
value: randomPrice(0, 1000),
type: 'Expense',
account: 'Utilities',
},
{
id: 3,
description: 'Order #5',
value: randomPrice(0, 1000),
type: 'Income',
account: 'Sales',
},
{
id: 4,
description: 'Google AdSense',
value: randomPrice(0, 1000),
type: 'Income',
account: 'Ads',
},
];
interface CustomTypeEditComponentProps extends GridEditSingleSelectCellProps {
setRows: React.Dispatch<React.SetStateAction<readonly any[]>>;
}
function CustomTypeEditComponent(props: CustomTypeEditComponentProps) {
const { setRows, ...other } = props;
const handleValueChange = () => {
setRows((prevRows) => {
console.log(prevRows);
return prevRows.map((row) =>
row.id === props.id ? { ...row, account: null } : row,
);
});
};
return <GridEditSingleSelectCell onValueChange={handleValueChange} {...other} />;
}
export default function LinkedFieldsCellEditing() {
const editingRow = React.useRef<GridRowModel | null>(null);
const [rows, setRows] = React.useState(initialRows);
const columns: GridColDef[] = [
{
field: 'description',
headerName: 'Description',
width: 160,
editable: true,
rowHeader: true,
},
{
field: 'value',
headerName: 'Value',
type: 'number',
width: 120,
editable: true,
},
{
field: 'type',
headerName: 'Type',
type: 'singleSelect',
valueOptions: ['Income', 'Expense'],
width: 120,
editable: true,
renderEditCell: (params) => (
<CustomTypeEditComponent setRows={setRows} {...params} />
),
},
{
field: 'account',
headerName: 'Account',
type: 'singleSelect',
valueOptions: ({ row }) => {
if (!row) {
return [
'Sales',
'Investments',
'Ads',
'Taxes',
'Payroll',
'Utilities',
'Marketing',
];
}
return row.type === 'Income'
? ['Sales', 'Investments', 'Ads']
: ['Taxes', 'Payroll', 'Utilities', 'Marketing'];
},
width: 140,
editable: true,
},
];
const handleCellEditStart: DataGridProps['onCellEditStart'] = (params) => {
editingRow.current = rows.find((row) => row.id === params.id) || null;
};
const handleCellEditStop: DataGridProps['onCellEditStop'] = (params) => {
if (params.reason === GridCellEditStopReasons.escapeKeyDown) {
setRows((prevRows) =>
prevRows.map((row) =>
row.id === editingRow.current?.id
? { ...row, account: editingRow.current?.account }
: row,
),
);
}
};
const processRowUpdate: DataGridProps['processRowUpdate'] = (newRow) => {
setRows((prevRows) =>
prevRows.map((row) => (row.id === editingRow.current?.id ? newRow : row)),
);
return newRow;
};
return (
<Box sx={{ width: '100%', height: 300 }}>
<DataGrid
rows={rows}
columns={columns}
onCellEditStart={handleCellEditStart}
onCellEditStop={handleCellEditStop}
processRowUpdate={processRowUpdate}
/>
</Box>
);
}
단일 클릭 편집
기본적으로 편집 모드에 들어가는 방법 중 하나는 셀을 더블클릭하는 거예요. 제어 모드를 사용하고 클릭 이벤트를 수신하면 단일 클릭으로도 편집 모드에 들어갈 수 있어요. 다음 데모는 이 동작을 구현해요.
import * as React from 'react';
import {
DataGrid,
GridCellModes,
GridCellModesModel,
GridCellParams,
GridRowsProp,
GridColDef,
} from '@mui/x-data-grid';
import {
randomCreatedDate,
randomTraderName,
randomUpdatedDate,
} from '@mui/x-data-grid-generator';
const columns: GridColDef[] = [
{ field: 'name', headerName: 'Name', width: 180, editable: true, rowHeader: true },
{ field: 'age', headerName: 'Age', type: 'number', editable: true },
{
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(),
},
];
export default function SingleClickEditing() {
const [cellModesModel, setCellModesModel] = React.useState<GridCellModesModel>({});
const handleCellClick = React.useCallback(
(params: GridCellParams, event: React.MouseEvent) => {
if (!params.isEditable) {
return;
}
// Ignore portal
if (
(event.target as any).nodeType === 1 &&
!event.currentTarget.contains(event.target as Element)
) {
return;
}
setCellModesModel((prevModel) => {
return {
// Revert the mode of the other cells from other rows
...Object.keys(prevModel).reduce(
(acc, id) => ({
...acc,
[id]: Object.keys(prevModel[id]).reduce(
(acc2, field) => ({
...acc2,
[field]: { mode: GridCellModes.View },
}),
{},
),
}),
{},
),
[params.id]: {
// Revert the mode of other cells in the same row
...Object.keys(prevModel[params.id] || {}).reduce(
(acc, field) => ({ ...acc, [field]: { mode: GridCellModes.View } }),
{},
),
[params.field]: { mode: GridCellModes.Edit },
},
};
});
},
[],
);
const handleCellModesModelChange = React.useCallback(
(newModel: GridCellModesModel) => {
setCellModesModel(newModel);
},
[],
);
return (
<div style={{ height: 300, width: '100%' }}>
<DataGrid
rows={rows}
columns={columns}
cellModesModel={cellModesModel}
onCellModesModelChange={handleCellModesModelChange}
onCellClick={handleCellClick}
/>
</div>
);
}
일괄 편집
Data Grid 편집(Editing) API는 행 단위로 편집을 저장하는 데 흔히 사용되는 the processRowUpdate 콜백을 노출해요.
이 콜백을 활용해 편집을 로컬에서 배치한 다음 일괄로 저장하거나 버릴 수 있어요.
아래 데모는 편집되고 삭제된 행을 unsavedChangesRef에 저장해요.
사용자가 Save 또는 Discard 버튼을 클릭하면 이 변경들이 각각 저장되거나 버려져요.
/* eslint-disable no-underscore-dangle */
import * as React from 'react';
import {
DataGrid,
GridRowId,
GridValidRowModel,
DataGridProps,
useGridApiRef,
GridActionsCellItem,
GridColDef,
gridClasses,
GridActionsCell,
GridRenderCellParams,
useGridApiContext,
} from '@mui/x-data-grid';
import { useDemoData } from '@mui/x-data-grid-generator';
import Button from '@mui/material/Button';
import DeleteIcon from '@mui/icons-material/Delete';
import RestoreIcon from '@mui/icons-material/Restore';
import SaveIcon from '@mui/icons-material/Save';
import { darken } from '@mui/material/styles';
const visibleFields = [
'id',
'commodity',
'traderName',
'traderEmail',
'quantity',
'filledQuantity',
];
interface UnsavedChanges {
unsavedRows: Record<GridRowId, GridValidRowModel>;
rowsBeforeChange: Record<GridRowId, GridValidRowModel>;
}
interface BulkEditingContextValue {
unsavedChangesRef: React.RefObject<UnsavedChanges>;
setHasUnsavedRows: (hasUnsavedRows: boolean) => void;
}
const BulkEditingContext = React.createContext<BulkEditingContextValue | null>(null);
function ActionsCell(props: GridRenderCellParams) {
const context = React.useContext(BulkEditingContext);
const apiRef = useGridApiContext();
if (!context) {
return null;
}
const { unsavedChangesRef, setHasUnsavedRows } = context;
const { id, row } = props;
return (
<GridActionsCell {...props}>
<GridActionsCellItem
icon={<RestoreIcon />}
label="Discard changes"
disabled={unsavedChangesRef.current.unsavedRows[id] === undefined}
onClick={() => {
apiRef.current?.updateRows([
unsavedChangesRef.current.rowsBeforeChange[id],
]);
delete unsavedChangesRef.current.rowsBeforeChange[id];
delete unsavedChangesRef.current.unsavedRows[id];
setHasUnsavedRows(
Object.keys(unsavedChangesRef.current.unsavedRows).length > 0,
);
}}
/>
<GridActionsCellItem
icon={<DeleteIcon />}
label="Delete"
onClick={() => {
unsavedChangesRef.current.unsavedRows[id] = {
...row,
_action: 'delete',
};
if (!unsavedChangesRef.current.rowsBeforeChange[id]) {
unsavedChangesRef.current.rowsBeforeChange[id] = row;
}
setHasUnsavedRows(true);
apiRef.current?.updateRows([row]); // to trigger row render
}}
/>
</GridActionsCell>
);
}
export default function BulkEditing() {
const { data } = useDemoData({
dataSet: 'Commodity',
rowLength: 100,
maxColumns: 7,
editable: true,
visibleFields,
});
const apiRef = useGridApiRef();
const [hasUnsavedRows, setHasUnsavedRows] = React.useState(false);
const [isSaving, setIsSaving] = React.useState(false);
const unsavedChangesRef = React.useRef<UnsavedChanges>({
unsavedRows: {},
rowsBeforeChange: {},
});
const columns = React.useMemo<GridColDef[]>(() => {
return [
{
field: 'actions',
type: 'actions',
renderCell: (params) => <ActionsCell {...params} />,
},
...data.columns,
];
}, [data.columns]);
const processRowUpdate = React.useCallback<
NonNullable<DataGridProps['processRowUpdate']>
>((newRow, oldRow) => {
const rowId = newRow.id;
unsavedChangesRef.current.unsavedRows[rowId] = newRow;
if (!unsavedChangesRef.current.rowsBeforeChange[rowId]) {
unsavedChangesRef.current.rowsBeforeChange[rowId] = oldRow;
}
setHasUnsavedRows(true);
return newRow;
}, []);
const discardChanges = React.useCallback(() => {
setHasUnsavedRows(false);
Object.values(unsavedChangesRef.current.rowsBeforeChange).forEach((row) => {
apiRef.current?.updateRows([row]);
});
unsavedChangesRef.current = {
unsavedRows: {},
rowsBeforeChange: {},
};
}, [apiRef]);
const saveChanges = React.useCallback(async () => {
try {
// Persist updates in the database
setIsSaving(true);
await new Promise((resolve) => {
setTimeout(resolve, 1000);
});
setIsSaving(false);
const rowsToDelete = Object.values(
unsavedChangesRef.current.unsavedRows,
).filter((row) => row._action === 'delete');
if (rowsToDelete.length > 0) {
rowsToDelete.forEach((row) => {
apiRef.current?.updateRows([row]);
});
}
setHasUnsavedRows(false);
unsavedChangesRef.current = {
unsavedRows: {},
rowsBeforeChange: {},
};
} catch (error) {
setIsSaving(false);
}
}, [apiRef]);
const getRowClassName = React.useCallback<
NonNullable<DataGridProps['getRowClassName']>
>(({ id }) => {
const unsavedRow = unsavedChangesRef.current.unsavedRows[id];
if (unsavedRow) {
if (unsavedRow._action === 'delete') {
return 'row--removed';
}
return 'row--edited';
}
return '';
}, []);
const bulkEditingContextValue = React.useMemo<BulkEditingContextValue>(
() => ({
unsavedChangesRef,
setHasUnsavedRows,
}),
[unsavedChangesRef],
);
return (
<div style={{ width: '100%' }}>
<div style={{ marginBottom: 8 }}>
<Button
disabled={!hasUnsavedRows}
loading={isSaving}
onClick={saveChanges}
startIcon={<SaveIcon />}
loadingPosition="start"
>
<span>Save</span>
</Button>
<Button
disabled={!hasUnsavedRows || isSaving}
onClick={discardChanges}
startIcon={<RestoreIcon />}
>
Discard all changes
</Button>
</div>
<div style={{ height: 400 }}>
<BulkEditingContext.Provider value={bulkEditingContextValue}>
<DataGrid
{...data}
columns={columns}
apiRef={apiRef}
disableRowSelectionOnClick
processRowUpdate={processRowUpdate}
ignoreValueFormatterDuringExport
sx={{
[`& .${gridClasses.row}.row--removed`]: {
backgroundColor: (theme) => {
if (theme.palette.mode === 'light') {
return 'rgba(255, 170, 170, 0.3)';
}
return darken('rgba(255, 170, 170, 1)', 0.7);
},
},
[`& .${gridClasses.row}.row--edited`]: {
backgroundColor: (theme) => {
if (theme.palette.mode === 'light') {
return 'rgba(255, 254, 176, 0.3)';
}
return darken('rgba(255, 254, 176, 1)', 0.6);
},
},
}}
loading={isSaving}
getRowClassName={getRowClassName}
/>
</BulkEditingContext.Provider>
</div>
</div>
);
}
상업용 기능 포함
Data Grid Premium을 사용하면 Clipboard paste는 지속성에 Editing API를 사용하므로, 일괄 편집이 Clipboard paste의 행 업데이트에 자동으로 적용돼요:
/* eslint-disable no-underscore-dangle */
import * as React from 'react';
import {
DataGridPremium,
GridRowId,
GridValidRowModel,
DataGridPremiumProps,
useGridApiRef,
GridActionsCellItem,
GridColDef,
gridClasses,
GridActionsCell,
GridRenderCellParams,
useGridApiContext,
} from '@mui/x-data-grid-premium';
import { useDemoData } from '@mui/x-data-grid-generator';
import Button from '@mui/material/Button';
import DeleteIcon from '@mui/icons-material/Delete';
import RestoreIcon from '@mui/icons-material/Restore';
import SaveIcon from '@mui/icons-material/Save';
import { darken } from '@mui/material/styles';
const visibleFields = [
'id',
'commodity',
'traderName',
'traderEmail',
'quantity',
'filledQuantity',
];
interface UnsavedChanges {
unsavedRows: Record<GridRowId, GridValidRowModel>;
rowsBeforeChange: Record<GridRowId, GridValidRowModel>;
}
interface BulkEditingContextValue {
unsavedChangesRef: React.RefObject<UnsavedChanges>;
setHasUnsavedRows: (hasUnsavedRows: boolean) => void;
}
const BulkEditingContext = React.createContext<BulkEditingContextValue | null>(null);
function ActionsCell(props: GridRenderCellParams) {
const context = React.useContext(BulkEditingContext);
const apiRef = useGridApiContext();
if (!context) {
return null;
}
const { unsavedChangesRef, setHasUnsavedRows } = context;
const { id, row } = props;
return (
<GridActionsCell {...props}>
<GridActionsCellItem
icon={<RestoreIcon />}
label="Discard changes"
disabled={unsavedChangesRef.current.unsavedRows[id] === undefined}
onClick={() => {
apiRef.current?.updateRows([
unsavedChangesRef.current.rowsBeforeChange[id],
]);
delete unsavedChangesRef.current.rowsBeforeChange[id];
delete unsavedChangesRef.current.unsavedRows[id];
setHasUnsavedRows(
Object.keys(unsavedChangesRef.current.unsavedRows).length > 0,
);
}}
/>
<GridActionsCellItem
icon={<DeleteIcon />}
label="Delete"
onClick={() => {
unsavedChangesRef.current.unsavedRows[id] = {
...row,
_action: 'delete',
};
if (!unsavedChangesRef.current.rowsBeforeChange[id]) {
unsavedChangesRef.current.rowsBeforeChange[id] = row;
}
setHasUnsavedRows(true);
apiRef.current?.updateRows([row]); // to trigger row render
}}
/>
</GridActionsCell>
);
}
export default function BulkEditingPremiumNoSnap() {
const { data } = useDemoData({
dataSet: 'Commodity',
rowLength: 100,
maxColumns: 7,
editable: true,
visibleFields,
});
const apiRef = useGridApiRef();
const [hasUnsavedRows, setHasUnsavedRows] = React.useState(false);
const [isSaving, setIsSaving] = React.useState(false);
const unsavedChangesRef = React.useRef<UnsavedChanges>({
unsavedRows: {},
rowsBeforeChange: {},
});
const columns = React.useMemo<GridColDef[]>(() => {
return [
{
field: 'actions',
type: 'actions',
renderCell: (params) => <ActionsCell {...params} />,
},
...data.columns,
];
}, [data.columns]);
const processRowUpdate = React.useCallback<
NonNullable<DataGridPremiumProps['processRowUpdate']>
>((newRow, oldRow) => {
const rowId = newRow.id;
unsavedChangesRef.current.unsavedRows[rowId] = newRow;
if (!unsavedChangesRef.current.rowsBeforeChange[rowId]) {
unsavedChangesRef.current.rowsBeforeChange[rowId] = oldRow;
}
setHasUnsavedRows(true);
return newRow;
}, []);
const discardChanges = React.useCallback(() => {
setHasUnsavedRows(false);
apiRef.current?.updateRows(
Object.values(unsavedChangesRef.current.rowsBeforeChange),
);
unsavedChangesRef.current = {
unsavedRows: {},
rowsBeforeChange: {},
};
}, [apiRef]);
const saveChanges = React.useCallback(async () => {
try {
// Persist updates in the database
setIsSaving(true);
await new Promise((resolve) => {
setTimeout(resolve, 1000);
});
setIsSaving(false);
const rowsToDelete = Object.values(
unsavedChangesRef.current.unsavedRows,
).filter((row) => row._action === 'delete');
if (rowsToDelete.length > 0) {
apiRef.current?.updateRows(rowsToDelete);
}
setHasUnsavedRows(false);
unsavedChangesRef.current = {
unsavedRows: {},
rowsBeforeChange: {},
};
} catch (error) {
setIsSaving(false);
}
}, [apiRef]);
const getRowClassName = React.useCallback<
NonNullable<DataGridPremiumProps['getRowClassName']>
>(({ id }) => {
const unsavedRow = unsavedChangesRef.current.unsavedRows[id];
if (unsavedRow) {
if (unsavedRow._action === 'delete') {
return 'row--removed';
}
return 'row--edited';
}
return '';
}, []);
const bulkEditingContextValue = React.useMemo<BulkEditingContextValue>(
() => ({
unsavedChangesRef,
setHasUnsavedRows,
}),
[unsavedChangesRef],
);
return (
<div style={{ width: '100%' }}>
<div style={{ marginBottom: 8 }}>
<Button
disabled={!hasUnsavedRows}
loading={isSaving}
onClick={saveChanges}
startIcon={<SaveIcon />}
loadingPosition="start"
>
<span>Save</span>
</Button>
<Button
disabled={!hasUnsavedRows || isSaving}
onClick={discardChanges}
startIcon={<RestoreIcon />}
>
Discard all changes
</Button>
</div>
<div style={{ height: 400 }}>
<BulkEditingContext.Provider value={bulkEditingContextValue}>
<DataGridPremium
{...data}
columns={columns}
apiRef={apiRef}
disableRowSelectionOnClick
cellSelection
processRowUpdate={processRowUpdate}
ignoreValueFormatterDuringExport
sx={{
[`& .${gridClasses.row}.row--removed`]: {
backgroundColor: (theme) => {
if (theme.palette.mode === 'light') {
return 'rgba(255, 170, 170, 0.3)';
}
return darken('rgba(255, 170, 170, 1)', 0.7);
},
},
[`& .${gridClasses.row}.row--edited`]: {
backgroundColor: (theme) => {
if (theme.palette.mode === 'light') {
return 'rgba(255, 254, 176, 0.3)';
}
return darken('rgba(255, 254, 176, 1)', 0.6);
},
},
}}
loading={isSaving}
getRowClassName={getRowClassName}
/>
</BulkEditingContext.Provider>
</div>
</div>
);
}