Data Grid - 드래그 앤 드롭 행 순서 변경 [<span class="plan-pro"></span>](/x/introduction/licensing/#pro-plan 'Pro plan')
Data Grid - 드래그 앤 드롭 행 순서 변경
Data Grid Pro를 사용하면 사용자가 행을 드래그 앤 드롭해서 순서를 바꿀 수 있어요.
본문
기본적으로 Data Grid에서 사용자는 행을 수동으로 재배열할 수 없어요. Data Grid Pro를 사용하면 사용자에게 행을 드래그 앤 드롭해서 순서를 바꾸는 기능을 줄 수 있어요.
행 순서 변경 구현하기
드래그 앤 드롭 행 순서 변경을 활성화하려면 Data Grid Pro에 rowReordering prop을 전달하세요:
<DataGridPro rowReordering />
이렇게 하면 각 행의 시작 부분에 드래그 표시용 새 열이 생성돼요:
import * as React from 'react';
import {
DataGridPro,
GridRowModel,
GridRowOrderChangeParams,
} from '@mui/x-data-grid-pro';
import { useDemoData } from '@mui/x-data-grid-generator';
function updateRowPosition(
initialIndex: number,
newIndex: number,
rows: Array<GridRowModel>,
): Promise<any> {
return new Promise((resolve) => {
setTimeout(
() => {
const rowsClone = [...rows];
const row = rowsClone.splice(initialIndex, 1)[0];
rowsClone.splice(newIndex, 0, row);
resolve(rowsClone);
},
// eslint-disable-next-line no-restricted-properties -- simulates network latency
Math.random() * 500 + 100,
);
});
}
export default function RowOrderingGrid() {
const { data, loading: initialLoadingState } = useDemoData({
dataSet: 'Commodity',
rowLength: 20,
maxColumns: 20,
});
const [rows, setRows] = React.useState(data.rows);
const [loading, setLoading] = React.useState(initialLoadingState);
React.useEffect(() => {
setRows(data.rows);
}, [data]);
React.useEffect(() => {
setLoading(initialLoadingState);
}, [initialLoadingState]);
const handleRowOrderChange = async (params: GridRowOrderChangeParams) => {
setLoading(true);
const newRows = await updateRowPosition(
params.oldIndex,
params.targetIndex,
rows,
);
setRows(newRows);
setLoading(false);
};
return (
<div style={{ height: 400, width: '100%' }}>
<DataGridPro
{...data}
loading={loading}
rows={rows}
rowReordering
onRowOrderChange={handleRowOrderChange}
/>
</div>
);
}
행 순서 변경 이벤트
드래그된 행의 순서 변경을 포착하려면 onRowOrderChange prop에 콜백을 전달할 수 있어요.
이 콜백은 GridRowOrderChangeParams 객체와 함께 호출돼요.
행 순서 변경은 다음 이벤트를 발생시켜요:
rowDragStart: 사용자가 행 드래그를 시작할 때 발생해요.rowDragOver: 사용자가 행을 다른 행 위로 드래그할 때 발생해요.rowDragEnd: 사용자가 행 드래그를 멈출 때 발생해요.
행 순서 변경 값 커스터마이징
기본적으로 사용자가 행 드래그를 시작하면 드래그 가능한 박스에 행의 ID가 표시돼요.
이것을 커스터마이징하려면 아래와 같이 각 행의 __reorder__ 필드에 값을 전달할 수 있어요:
const columns: GridColDef[] = [{ field: 'brand' }];
const rows: GridRowsProp = [
{ id: 0, brand: 'Nike', __reorder__: 'Nike' },
{ id: 1, brand: 'Adidas', __reorder__: 'Adidas' },
{ id: 2, brand: 'Puma', __reorder__: 'Puma' },
];
<DataGridPro rows={rows} columns={columns} rowReordering />;
드래그 표시자 커스터마이징
드래그 표시자 열에 사용되는 아이콘을 변경하려면 아이콘 슬롯에 다른 컴포넌트를 제공할 수 있어요:
<DataGridPro
slots={{
rowReorderIcon: CustomMoveIcon,
}}
/>
또는 열 집합에 field: __reorder__ 열을 추가할 수 있어요.
이렇게 하면 GRID_REORDER_COL_DEF 열의 속성을 모두 재정의할 수 있어요.
Grid는 이미 순서 변경 열이 정의되어 있음을 감지하므로 기본 위치에 다른 열을 추가하지 않아요.
field만 설정하면 나머지 옵션(열 메뉴, 필터링, 정렬 비활성화 등)을 직접 구성해야 해요.
이 구성으로 시작하려면 열을 정의할 때 GRID_REORDER_COL_DEF를 펼쳐(spread) 사용하세요:
<DataGridPro
columns={[
{
...GRID_REORDER_COL_DEF, // Already contains the right field
width: 40,
},
]}
/>
이 방법은 토글 열의 위치를 변경하는 데에도 사용할 수 있어요.
:::warning 현재 Data Grid에 정렬이 적용되어 있으면 행 순서 변경은 비활성화돼요. :::
특정 행의 순서 변경 비활성화
특정 행의 순서 변경을 비활성화하려면 isRowReorderable() prop에 콜백을 전달할 수 있어요.
이 콜백은 row와 rowNode 객체와 함께 호출되므로 여러 기준에 따라 행을 비활성화할 수 있어요.
const isRowReorderable = (params: IsRowReorderableParams) => {
// Example: Disable reordering if the quantity is greater than 50000
return params.row.quantity > 50000;
};
<DataGridPro isRowReorderable={isRowReorderable} />;
아래 데모는 행 모델을 기준으로 특정 행의 순서 변경을 비활성화하는 방법을 보여줘요.
import * as React from 'react';
import { DataGridPro, type IsRowReorderableParams } from '@mui/x-data-grid-pro';
import { useDemoData } from '@mui/x-data-grid-generator';
const isRowReorderable = (params: IsRowReorderableParams) => {
return params.row.quantity < 50000;
};
export default function RowReorderingDisabled() {
const { data, loading } = useDemoData({
dataSet: 'Commodity',
rowLength: 20,
maxColumns: 20,
});
return (
<div style={{ height: 400, width: '100%' }}>
<DataGridPro
{...data}
loading={loading}
rowReordering
isRowReorderable={isRowReorderable}
/>
</div>
);
}
특정 순서 변경 작업 비활성화
때로는 원본 행이 제공하는 정보만으로 순서 변경 작업이 유효한지 판단하기에 부족할 수 있어요.
이런 경우 isValidRowReorder() prop에 콜백을 전달할 수 있어요.
이 콜백은 드래그 작업 중에 실행되므로 드래그된 행과 그것을 놓을 수 있는 잠재적 위치에 대한 정보를 제공해요.
ReorderValidationContext 객체와 함께 호출되므로 컨텍스트에 따라 특정 순서 변경 작업을 비활성화할 수 있어요.
아래 데모는 같은 부모 아래의 리프(leaf) 행 순서 변경을 금지하고 부모 간 작업만 허용해요.
import * as React from 'react';
import {
DataGridPro,
GridValidRowModel,
ReorderValidationContext,
} from '@mui/x-data-grid-pro';
import { useDemoData } from '@mui/x-data-grid-generator';
const isValidRowReorder = (context: ReorderValidationContext) => {
if (context.sourceNode.type === 'group') {
return true;
}
if (
context.targetNode.type === 'group' &&
context.targetNode.id !== context.sourceNode.parent &&
context.dropPosition === 'inside'
) {
return true;
}
if (context.targetNode.type === 'leaf') {
return context.sourceNode.parent !== context.targetNode.parent;
}
return false;
};
const getTreeDataPath = (row: GridValidRowModel) => {
return row.path;
};
const setTreeDataPath = (path: string[], row: GridValidRowModel) => {
return { ...row, path };
};
export default function RowReorderingValidation() {
const { data, loading } = useDemoData({
dataSet: 'Employee',
rowLength: 100,
treeData: { maxDepth: 2, groupingField: 'name', averageChildren: 4 },
});
return (
<div style={{ height: 400, width: '100%' }}>
<DataGridPro
{...data}
setTreeDataPath={setTreeDataPath}
getTreeDataPath={getTreeDataPath}
loading={loading}
rowReordering
isValidRowReorder={isValidRowReorder}
/>
</div>
);
}
:::warning
행 순서 변경 기능은 지원되는 사용 사례만 허용되도록 내부 검증 규칙 집합을 가지고 있어요.
isValidRowReorder()는 검증 규칙을 추가하는 용도로만 사용해야 해요.
:::
트리 데이터와 함께 행 순서 변경
사용자는 행을 드래그 앤 드롭해서 부모 사이를 이동하거나, 리프 노드를 부모 그룹으로 변환할 수 있어요.
자세한 내용은 Tree data—드래그 앤 드롭 트리 데이터 순서 변경을 참고하세요.
행 그룹화와 함께 행 순서 변경
이 기능을 사용하면 사용자가 그룹화된 데이터 내에서 행을 순서 변경하여 그리드에서 바로 그룹과 그 내용의 순서를 조정할 수 있어요.
자세한 내용은 Row grouping—드래그 앤 드롭 그룹 순서 변경을 참고하세요.