Data Grid - 트리 데이터
Data Grid - 트리 데이터 (Tree data)
트리 데이터를 사용하여 Data Grid에서 부모-자식 관계를 가진 행을 렌더링합니다.
트리는 데이터를 부모-자식 관계로 구성하는 계층적 데이터 구조입니다. Data Grid Pro는 이 패턴에 맞는 행을 렌더링하기 위해 트리 데이터를 사용할 수 있습니다. 아래 데모는 크고 복잡한 계층적 데이터셋으로 이 기능을 보여줍니다:
import { DataGridPro, useGridApiRef } from '@mui/x-data-grid-pro';
import { useDemoData } from '@mui/x-data-grid-generator';
import Button from '@mui/material/Button';
export default function TreeDataFullExample() {
const apiRef = useGridApiRef();
const { data, loading } = useDemoData({
dataSet: 'Employee',
rowLength: 1000,
treeData: { maxDepth: 2, groupingField: 'name', averageChildren: 200 },
});
return (
<div style={{ width: '100%' }}>
<Button onClick={() => apiRef.current?.expandAllRows()}>Expand all</Button>
<Button onClick={() => apiRef.current?.collapseAllRows()}>Collapse all</Button>
<div style={{ height: 400 }}>
<DataGridPro loading={loading} {...data} apiRef={apiRef} />
</div>
</div>
);
}
:::info 이 문서는 클라이언트 측 데이터를 다룹니다. 서버 측 트리 데이터는 Server-side data—Tree data를 참고하세요. :::
트리 데이터 렌더링
트리 데이터를 사용하려면 <DataGridPro /> 컴포넌트에 treeData와 getTreeDataPath props를 전달합니다.
getTreeDataPath 함수는 주어진 행까지의 경로를 나타내는 문자열 배열을 반환합니다.
<DataGridPro treeData getTreeDataPath={getTreeDataPath} />
다음 두 예시 모두 이런 모양의 트리를 렌더링합니다:
// - Sarah
// - Thomas
// - Robert
// - Karen
1. 변환 없이:
const columns: GridColDef[] = [{ field: 'jobTitle', width: 250 }];
const rows: GridRowsProp = [
{ path: ['Sarah'], jobTitle: 'CEO', id: 0 },
{ path: ['Sarah', 'Thomas'], jobTitle: 'Head of Sales', id: 1 },
{ path: ['Sarah', 'Thomas', 'Robert'], jobTitle: 'Sales Person', id: 2 },
{ path: ['Sarah', 'Thomas', 'Karen'], jobTitle: 'Sales Person', id: 3 },
];
const getTreeDataPath: DataGridProProps['getTreeDataPath'] = (row) => row.path;
<DataGridPro
treeData
getTreeDataPath={getTreeDataPath}
rows={rows}
columns={columns}
/>;
2. 변환과 함께:
const columns: GridColDef[] = [{ field: 'jobTitle', width: 250 }];
const rows: GridRowsProp = [
{ path: 'Sarah', jobTitle: 'CEO', id: 0 },
{ path: 'Sarah/Thomas', jobTitle: 'Head of Sales', id: 1 },
{ path: 'Sarah/Thomas/Robert', jobTitle: 'Sales Person', id: 2 },
{ path: 'Sarah/Thomas/Karen', jobTitle: 'Sales Person', id: 3 },
];
const getTreeDataPath: DataGridProProps['getTreeDataPath'] = (row) =>
row.path.split('/');
<DataGridPro
treeData
getTreeDataPath={getTreeDataPath}
rows={rows}
columns={columns}
/>;
:::warning
getTreeDataPath prop은 두 렌더링 사이에 동일한 참조를 유지해야 합니다.
변경되면 Data Grid는 데이터 자체가 변경된 것으로 간주하고 트리를 다시 계산하여 모든 행이 접히게 됩니다.
:::
트리 데이터로 그룹화 열 커스터마이즈
그룹화 열 커스터마이즈에 대한 전체 세부 사항은 Row grouping—Grouping columns을 참고하세요.
트리 데이터 작업 시 구현과 동작은 동일하지만, leafField와 mainGroupingCriteria props는 적용되지 않는다는 점에 유의하세요.
아래 데모는 Hierarchy 그룹화 열을 커스터마이즈합니다:
import {
DataGridPro,
GridRenderCellParams,
useGridApiContext,
GridColDef,
GridRowsProp,
DataGridProProps,
useGridSelector,
gridFilteredDescendantCountLookupSelector,
} from '@mui/x-data-grid-pro';
import Box from '@mui/material/Box';
import Button, { ButtonProps } from '@mui/material/Button';
export const isNavigationKey = (key: string) =>
key === 'Home' ||
key === 'End' ||
key.indexOf('Arrow') === 0 ||
key.indexOf('Page') === 0 ||
key === ' ';
function CustomGridTreeDataGroupingCell(props: GridRenderCellParams) {
const { id, field, rowNode } = props;
const apiRef = useGridApiContext();
const filteredDescendantCountLookup = useGridSelector(
apiRef,
gridFilteredDescendantCountLookupSelector,
);
const filteredDescendantCount = filteredDescendantCountLookup[rowNode.id] ?? 0;
const handleClick: ButtonProps['onClick'] = (event) => {
if (rowNode.type !== 'group') {
return;
}
apiRef.current.setRowChildrenExpansion(id, !rowNode.childrenExpanded);
apiRef.current.setCellFocus(id, field);
event.stopPropagation();
};
return (
<Box sx={{ ml: rowNode.depth * 4 }}>
<div>
{filteredDescendantCount > 0 ? (
<Button onClick={handleClick} tabIndex={-1} size="small">
See {filteredDescendantCount} employees
</Button>
) : (
<span />
)}
</div>
</Box>
);
}
interface Row {
hierarchy: string[];
jobTitle: string;
recruitmentDate: Date;
id: number;
}
const rows: GridRowsProp<Row> = [
{
hierarchy: ['Sarah'],
jobTitle: 'Head of Human Resources',
recruitmentDate: new Date(2020, 8, 12),
id: 0,
},
{
hierarchy: ['Thomas'],
jobTitle: 'Head of Sales',
recruitmentDate: new Date(2017, 3, 4),
id: 1,
},
{
hierarchy: ['Thomas', 'Robert'],
jobTitle: 'Sales Person',
recruitmentDate: new Date(2020, 11, 20),
id: 2,
},
{
hierarchy: ['Thomas', 'Karen'],
jobTitle: 'Sales Person',
recruitmentDate: new Date(2020, 10, 14),
id: 3,
},
{
hierarchy: ['Thomas', 'Nancy'],
jobTitle: 'Sales Person',
recruitmentDate: new Date(2017, 10, 29),
id: 4,
},
{
hierarchy: ['Thomas', 'Daniel'],
jobTitle: 'Sales Person',
recruitmentDate: new Date(2020, 7, 21),
id: 5,
},
{
hierarchy: ['Thomas', 'Christopher'],
jobTitle: 'Sales Person',
recruitmentDate: new Date(2020, 7, 20),
id: 6,
},
{
hierarchy: ['Thomas', 'Donald'],
jobTitle: 'Sales Person',
recruitmentDate: new Date(2019, 6, 28),
id: 7,
},
{
hierarchy: ['Mary'],
jobTitle: 'Head of Engineering',
recruitmentDate: new Date(2016, 3, 14),
id: 8,
},
{
hierarchy: ['Mary', 'Jennifer'],
jobTitle: 'Tech lead front',
recruitmentDate: new Date(2016, 5, 17),
id: 9,
},
{
hierarchy: ['Mary', 'Jennifer', 'Anna'],
jobTitle: 'Front-end developer',
recruitmentDate: new Date(2019, 11, 7),
id: 10,
},
{
hierarchy: ['Mary', 'Michael'],
jobTitle: 'Tech lead devops',
recruitmentDate: new Date(2021, 7, 1),
id: 11,
},
{
hierarchy: ['Mary', 'Linda'],
jobTitle: 'Tech lead back',
recruitmentDate: new Date(2017, 0, 12),
id: 12,
},
{
hierarchy: ['Mary', 'Linda', 'Elizabeth'],
jobTitle: 'Back-end developer',
recruitmentDate: new Date(2019, 2, 22),
id: 13,
},
{
hierarchy: ['Mary', 'Linda', 'William'],
jobTitle: 'Back-end developer',
recruitmentDate: new Date(2018, 4, 19),
id: 14,
},
];
const columns: GridColDef<Row>[] = [
{
field: 'name',
headerName: 'Name',
valueGetter: (value, row) => {
const hierarchy = row.hierarchy;
return hierarchy[hierarchy.length - 1];
},
},
{ field: 'jobTitle', headerName: 'Job Title', width: 200 },
{
field: 'recruitmentDate',
headerName: 'Recruitment Date',
type: 'date',
width: 150,
},
];
const getTreeDataPath: DataGridProProps['getTreeDataPath'] = (row) => row.hierarchy;
const groupingColDef: DataGridProProps['groupingColDef'] = {
headerName: 'Hierarchy',
renderCell: (params) => <CustomGridTreeDataGroupingCell {...params} />,
};
export default function TreeDataCustomGroupingColumn() {
return (
<div style={{ height: 400, width: '100%' }}>
<DataGridPro
treeData
rows={rows}
columns={columns}
getTreeDataPath={getTreeDataPath}
groupingColDef={groupingColDef}
/>
</div>
);
}
그룹화 열 필드 접근
그룹화 열 필드에 접근하려면—예를 들어 열 고정과 함께 사용하기 위해—Grid는 GRID_TREE_DATA_GROUPING_FIELD 상수를 제공합니다:
<DataGridPro
treeData
initialState={{
pinnedColumns: {
left: [GRID_TREE_DATA_GROUPING_FIELD],
},
}}
{...otherProps}
/>
트리 데이터로 그룹 확장
그룹 확장 경험 커스터마이즈에 대한 전체 세부 사항은 Row grouping—Group expansion을 참고하세요. 트리 데이터 작업 시 구현과 동작은 동일합니다.
트리 데이터로 부모·자식 자동 선택
자동 부모·자식 선택에 대한 전체 세부 사항은 Row grouping—Automatic parent and child selection을 참고하세요. 트리 데이터 작업 시 구현과 동작은 동일합니다.
트리의 빈틈 (Gaps)
제공된 트리 데이터에 계층의 일부 레벨이 빠져 있다면, Data Grid Pro는 빈틈을 채우는 데 필요한 행을 자동으로 생성합니다. 두 개의 행이 있는 간단한 데이터셋을 생각해 보세요:
[{ path: ['A'] }, { path: ['A', 'B', 'C'] }];
이 트리 데이터는 존재하지 않는 { path: ["A", "B"] } 행을 암시합니다.
이를 해결하기 위해 Grid는 문제없이 렌더링할 수 있도록 내부 행을 생성합니다.
아래 데모에서 빈틈이 없는 행에는 Gap 열에 **✕**가 표시됩니다—데이터셋에 없으므로 Thomas, Mary, Linda의 행이 자동 생성된 것을 볼 수 있습니다.
import { DataGridPro, GridColDef, DataGridProProps } from '@mui/x-data-grid-pro';
const rows = [
{
hierarchy: ['Sarah'],
jobTitle: 'Head of Human Resources',
recruitmentDate: new Date(2020, 8, 12),
id: 0,
},
{
hierarchy: ['Thomas', 'Robert'],
jobTitle: 'Sales Person',
recruitmentDate: new Date(2020, 11, 20),
id: 2,
},
{
hierarchy: ['Thomas', 'Karen'],
jobTitle: 'Sales Person',
recruitmentDate: new Date(2020, 10, 14),
id: 3,
},
{
hierarchy: ['Thomas', 'Nancy'],
jobTitle: 'Sales Person',
recruitmentDate: new Date(2017, 10, 29),
id: 4,
},
{
hierarchy: ['Thomas', 'Daniel'],
jobTitle: 'Sales Person',
recruitmentDate: new Date(2020, 7, 21),
id: 5,
},
{
hierarchy: ['Thomas', 'Christopher'],
jobTitle: 'Sales Person',
recruitmentDate: new Date(2020, 7, 20),
id: 6,
},
{
hierarchy: ['Thomas', 'Donald'],
jobTitle: 'Sales Person',
recruitmentDate: new Date(2019, 6, 28),
id: 7,
},
{
hierarchy: ['Mary', 'Jennifer'],
jobTitle: 'Tech lead front',
recruitmentDate: new Date(2016, 5, 17),
id: 9,
},
{
hierarchy: ['Mary', 'Jennifer', 'Anna'],
jobTitle: 'Front-end developer',
recruitmentDate: new Date(2019, 11, 7),
id: 10,
},
{
hierarchy: ['Mary', 'Michael'],
jobTitle: 'Tech lead devops',
recruitmentDate: new Date(2021, 7, 1),
id: 11,
},
{
hierarchy: ['Mary', 'Linda', 'Elizabeth'],
jobTitle: 'Back-end developer',
recruitmentDate: new Date(2019, 2, 22),
id: 13,
},
{
hierarchy: ['Mary', 'Linda', 'William'],
jobTitle: 'Back-end developer',
recruitmentDate: new Date(2018, 4, 19),
id: 14,
},
];
const columns: GridColDef<(typeof rows)[number]>[] = [
{ field: 'jobTitle', headerName: 'Job Title', width: 200 },
{
field: 'recruitmentDate',
headerName: 'Recruitment Date',
type: 'date',
width: 150,
},
{
field: 'isAutoGenerated',
headerName: 'Gap',
type: 'boolean',
valueGetter: (value, row, column, apiRef) => {
const rowId = apiRef.current.getRowId(row);
const rowNode = apiRef.current.getRowNode(rowId);
if (rowNode?.type !== 'group') {
return undefined;
}
return rowNode.isAutoGenerated;
},
},
];
const getTreeDataPath: DataGridProProps['getTreeDataPath'] = (row) => row.hierarchy;
export default function TreeDataWithGap() {
return (
<div style={{ height: 400, width: '100%' }}>
<DataGridPro
treeData
rows={rows}
columns={columns}
getTreeDataPath={getTreeDataPath}
/>
</div>
);
}
트리 데이터 필터링
필터가 적용되면, 노드는 그것 또는 그 자손 중 하나라도 통과하면 포함됩니다.
기본적으로 필터링은 트리의 모든 레벨에 적용됩니다.
disableChildrenFiltering prop으로 최상위 행에만 제한할 수 있습니다.
import * as React from 'react';
import {
DataGridPro,
GridColDef,
GridFilterModel,
GridLogicOperator,
GridRowsProp,
DataGridProProps,
} from '@mui/x-data-grid-pro';
import Box from '@mui/material/Box';
import Checkbox from '@mui/material/Checkbox';
import FormGroup from '@mui/material/FormGroup';
import FormControlLabel from '@mui/material/FormControlLabel';
import Typography from '@mui/material/Typography';
const rows: GridRowsProp = [
{
hierarchy: ['Sarah'],
jobTitle: 'Head of Human Resources',
recruitmentDate: new Date(2020, 8, 12),
id: 0,
},
{
hierarchy: ['Thomas'],
jobTitle: 'Head of Sales',
recruitmentDate: new Date(2017, 3, 4),
id: 1,
},
{
hierarchy: ['Thomas', 'Robert'],
jobTitle: 'Sales Person',
recruitmentDate: new Date(2020, 11, 20),
id: 2,
},
{
hierarchy: ['Thomas', 'Karen'],
jobTitle: 'Sales Person',
recruitmentDate: new Date(2020, 10, 14),
id: 3,
},
{
hierarchy: ['Thomas', 'Nancy'],
jobTitle: 'Sales Person',
recruitmentDate: new Date(2017, 10, 29),
id: 4,
},
{
hierarchy: ['Thomas', 'Daniel'],
jobTitle: 'Sales Person',
recruitmentDate: new Date(2020, 7, 21),
id: 5,
},
{
hierarchy: ['Thomas', 'Christopher'],
jobTitle: 'Sales Person',
recruitmentDate: new Date(2020, 7, 20),
id: 6,
},
{
hierarchy: ['Thomas', 'Donald'],
jobTitle: 'Sales Person',
recruitmentDate: new Date(2019, 6, 28),
id: 7,
},
{
hierarchy: ['Mary'],
jobTitle: 'Head of Engineering',
recruitmentDate: new Date(2016, 3, 14),
id: 8,
},
{
hierarchy: ['Mary', 'Jennifer'],
jobTitle: 'Tech lead front',
recruitmentDate: new Date(2016, 5, 17),
id: 9,
},
{
hierarchy: ['Mary', 'Jennifer', 'Anna'],
jobTitle: 'Front-end developer',
recruitmentDate: new Date(2019, 11, 7),
id: 10,
},
{
hierarchy: ['Mary', 'Michael'],
jobTitle: 'Tech lead devops',
recruitmentDate: new Date(2021, 7, 1),
id: 11,
},
{
hierarchy: ['Mary', 'Linda'],
jobTitle: 'Tech lead back',
recruitmentDate: new Date(2017, 0, 12),
id: 12,
},
{
hierarchy: ['Mary', 'Linda', 'Elizabeth'],
jobTitle: 'Back-end developer',
recruitmentDate: new Date(2019, 2, 22),
id: 13,
},
{
hierarchy: ['Mary', 'Linda', 'William'],
jobTitle: 'Back-end developer',
recruitmentDate: new Date(2018, 4, 19),
id: 14,
},
];
const columns: GridColDef[] = [
{ field: 'jobTitle', headerName: 'Job Title', width: 200 },
{
field: 'recruitmentDate',
headerName: 'Recruitment Date',
type: 'date',
width: 150,
},
];
const getTreeDataPath: DataGridProProps['getTreeDataPath'] = (row) => row.hierarchy;
export default function TreeDataDisableChildrenFiltering() {
const [disableChildrenFiltering, setDisableChildrenFiltering] =
React.useState(true);
const [filterModel, setFilterModel] = React.useState<GridFilterModel>({
logicOperator: GridLogicOperator.Or,
items: [
{
id: 0,
field: 'recruitmentDate',
operator: 'before',
value: '2018-01-01',
},
],
});
return (
<Box sx={{ width: '100%' }}>
<FormGroup>
<FormControlLabel
control={
<Checkbox
checked={disableChildrenFiltering}
onChange={(event) => setDisableChildrenFiltering(event.target.checked)}
/>
}
label={
<Typography component="span">
Apply <code>disableChildrenFiltering</code>
</Typography>
}
/>
</FormGroup>
<Box sx={{ height: 400, pt: 1 }}>
<DataGridPro
treeData
rows={rows}
columns={columns}
disableChildrenFiltering={disableChildrenFiltering}
getTreeDataPath={getTreeDataPath}
filterModel={filterModel}
onFilterModelChange={setFilterModel}
defaultGroupingExpansionDepth={1}
/>
</Box>
</Box>
);
}
트리 데이터 정렬
기본적으로 정렬은 트리의 모든 레벨에 적용됩니다.
disableChildrenSorting prop으로 최상위 행에만 제한할 수 있습니다.
import * as React from 'react';
import {
DataGridPro,
GridColDef,
GridRowsProp,
GridSortModel,
DataGridProProps,
} from '@mui/x-data-grid-pro';
import Box from '@mui/material/Box';
import Checkbox from '@mui/material/Checkbox';
import FormGroup from '@mui/material/FormGroup';
import FormControlLabel from '@mui/material/FormControlLabel';
import Typography from '@mui/material/Typography';
const rows: GridRowsProp = [
{
hierarchy: ['Sarah'],
jobTitle: 'Head of Human Resources',
recruitmentDate: new Date(2020, 8, 12),
id: 0,
},
{
hierarchy: ['Thomas'],
jobTitle: 'Head of Sales',
recruitmentDate: new Date(2017, 3, 4),
id: 1,
},
{
hierarchy: ['Thomas', 'Robert'],
jobTitle: 'Sales Person',
recruitmentDate: new Date(2020, 11, 20),
id: 2,
},
{
hierarchy: ['Thomas', 'Karen'],
jobTitle: 'Sales Person',
recruitmentDate: new Date(2020, 10, 14),
id: 3,
},
{
hierarchy: ['Thomas', 'Nancy'],
jobTitle: 'Sales Person',
recruitmentDate: new Date(2017, 10, 29),
id: 4,
},
{
hierarchy: ['Thomas', 'Daniel'],
jobTitle: 'Sales Person',
recruitmentDate: new Date(2020, 7, 21),
id: 5,
},
{
hierarchy: ['Thomas', 'Christopher'],
jobTitle: 'Sales Person',
recruitmentDate: new Date(2020, 7, 20),
id: 6,
},
{
hierarchy: ['Thomas', 'Donald'],
jobTitle: 'Sales Person',
recruitmentDate: new Date(2019, 6, 28),
id: 7,
},
{
hierarchy: ['Mary'],
jobTitle: 'Head of Engineering',
recruitmentDate: new Date(2016, 3, 14),
id: 8,
},
{
hierarchy: ['Mary', 'Jennifer'],
jobTitle: 'Tech lead front',
recruitmentDate: new Date(2016, 5, 17),
id: 9,
},
{
hierarchy: ['Mary', 'Jennifer', 'Anna'],
jobTitle: 'Front-end developer',
recruitmentDate: new Date(2019, 11, 7),
id: 10,
},
{
hierarchy: ['Mary', 'Michael'],
jobTitle: 'Tech lead devops',
recruitmentDate: new Date(2021, 7, 1),
id: 11,
},
{
hierarchy: ['Mary', 'Linda'],
jobTitle: 'Tech lead back',
recruitmentDate: new Date(2017, 0, 12),
id: 12,
},
{
hierarchy: ['Mary', 'Linda', 'Elizabeth'],
jobTitle: 'Back-end developer',
recruitmentDate: new Date(2019, 2, 22),
id: 13,
},
{
hierarchy: ['Mary', 'Linda', 'William'],
jobTitle: 'Back-end developer',
recruitmentDate: new Date(2018, 4, 19),
id: 14,
},
];
const columns: GridColDef[] = [
{ field: 'jobTitle', headerName: 'Job Title', width: 200 },
{
field: 'recruitmentDate',
headerName: 'Recruitment Date',
type: 'date',
width: 150,
},
];
const getTreeDataPath: DataGridProProps['getTreeDataPath'] = (row) => row.hierarchy;
export default function TreeDataDisableChildrenSorting() {
const [disableChildrenSorting, setDisableChildrenSorting] = React.useState(true);
const [sortModel, setSortModel] = React.useState<GridSortModel>([
{ field: 'recruitmentDate', sort: 'asc' },
]);
return (
<Box sx={{ width: '100%' }}>
<FormGroup>
<FormControlLabel
control={
<Checkbox
checked={disableChildrenSorting}
onChange={(event) => setDisableChildrenSorting(event.target.checked)}
/>
}
label={
<Typography component="span">
Apply <code>disableChildrenSorting</code>
</Typography>
}
/>
</FormGroup>
<Box sx={{ height: 400, mt: 1 }}>
<DataGridPro
treeData
rows={rows}
columns={columns}
disableChildrenSorting={disableChildrenSorting}
getTreeDataPath={getTreeDataPath}
sortModel={sortModel}
onSortModelChange={setSortModel}
defaultGroupingExpansionDepth={-1}
/>
</Box>
</Box>
);
}
:::warning
sortingMode="server"를 사용할 때 자식은 항상 부모 바로 뒤에 와야 합니다:
// ✅ Row A.A immediately follows its parent
const validRows = [{ path: ['A'] }, { path: ['A', 'A'] }, { path: ['B'] }];
// ❌ Row X.X does not immediately follow its parent
const invalidRows = [{ path: ['X'] }, { path: ['Y'] }, { path: ['X', 'X'] }];
:::
드래그 앤 드롭 트리 데이터 재정렬
행 재정렬을 사용하면 사용자가 트리 데이터를 재정렬하거나 행을 한 그룹에서 다른 그룹으로 이동할 수 있습니다.
트리 데이터에서 이 기능을 활성화하려면 Data Grid 컴포넌트에 rowReordering prop을 전달하세요.
또한 행 재정렬이 행의 경로를 변경할 수 있으므로, 트리를 만드는 동안 getTreeDataPath가 수행한 작업을 되돌리려면 setTreeDataPath prop을 전달해야 합니다.
<DataGridPro
columns={columns}
rows={rows}
treeData
getTreeDataPath={getTreeDataPath}
setTreeDataPath={setTreeDataPath}
rowReordering
/>
import * as React from 'react';
import { DataGridPro, type DataGridProProps } from '@mui/x-data-grid-pro';
import { useDemoData } from '@mui/x-data-grid-generator';
const getTreeDataPath: DataGridProProps['getTreeDataPath'] = (row) => {
return row.path;
};
const setTreeDataPath: DataGridProProps['setTreeDataPath'] = (path, row) => {
return {
...row,
path,
};
};
export default function TreeDataReordering() {
const { data, loading } = useDemoData({
dataSet: 'Employee',
rowLength: 100,
treeData: { maxDepth: 3, groupingField: 'name', averageChildren: 2 },
});
return (
<div style={{ height: 400, width: '100%' }}>
<DataGridPro
{...data}
loading={loading}
rowReordering
disableRowSelectionOnClick
getTreeDataPath={getTreeDataPath}
setTreeDataPath={setTreeDataPath}
/>
</div>
);
}
재정렬 지속성
업데이트된 행 순서를 외부 저장소와 동기화하려면, 외부 저장소에서 행 순서를 관리하는 방식에 따라 processRowUpdate() 또는 onRowOrderChange() 콜백(또는 둘 다)을 사용할 수 있습니다.
processRowUpdate() 콜백은 행 편집으로 행이 업데이트되거나, 교차 부모 재정렬 작업 중 path 값이 업데이트될 때마다 트리거됩니다.
재정렬 작업이 성공적으로 완료된 후 onRowOrderChange() 콜백이 트리거되며, 여기에는 GridRowOrderChangeParams 형식의 새 행 재정렬 정보가 포함됩니다.
<DataGridPro
// Fired when:
// - A row is edited (e.g. when the user changes the value of a cell)
// - The `path` value is updated during a cross parent reorder operation
processRowUpdate={processRowUpdate}
// Fired after a reorder operation is completed
onRowOrderChange={handleRowOrderChange}
/>
아래 데모는 useSyncExternalStore()로 바인딩된 사용자 정의 데이터 저장소를 사용하여 행 데이터를 로컬 저장소에 지속합니다.
재정렬 작업을 수행한 후 경로 값을 다시 계산하는 데 사용되는 행 트리 구조를 유지하며, 다음 props는 업데이트된 행 순서를 외부 저장소와 동기화하는 데 사용됩니다:
processRowUpdate(): 행이 편집될 때 행 데이터를 업데이트하는 데 사용됩니다(동적 경로 계산 덕분에path값 변경은 필요 없습니다. 정적 경로의 경우path값도 동기화해야 할 수 있습니다).onRowOrderChange(): 재정렬 작업을 수행한 후 새 행 순서를 캡처하고 새 행 순서로 외부 저장소를 업데이트하는 데 사용됩니다.
행을 재정렬한 후 페이지를 새로 고쳐 순서가 지속되는지 데모를 테스트해 볼 수 있습니다.
import * as React from 'react';
import {
DataGridPro,
useGridApiRef,
type DataGridProProps,
} from '@mui/x-data-grid-pro';
import Button from '@mui/material/Button';
import { TreeDataSyncRowDataGroupingCell } from './utils/TreeDataSyncRowDataGroupingCell';
import { DataStore } from './utils/DataStore';
export default function TreeDataSyncRowData() {
const apiRef = useGridApiRef();
const dataStore = React.useMemo(() => new DataStore(), []);
const { rows, loading } = React.useSyncExternalStore(
dataStore.subscribe,
dataStore.getSnapshot,
dataStore.getSnapshot,
);
return (
<div
style={{ width: '100%', display: 'flex', flexDirection: 'column', gap: 10 }}
>
<Button variant="outlined" onClick={() => dataStore.reset()}>
Reset Local Storage Data
</Button>
<div style={{ height: 400 }}>
<DataGridPro
apiRef={apiRef}
loading={loading}
rows={rows}
columns={columns}
treeData
rowReordering
isValidRowReorder={isValidRowReorder}
disableRowSelectionOnClick
onRowOrderChange={dataStore.handleRowOrderChange}
processRowUpdate={dataStore.processRowUpdate}
getTreeDataPath={getTreeDataPath}
setTreeDataPath={setTreeDataPath}
groupingColDef={groupingColDef}
/>
</div>
</div>
);
}
const columns: DataGridProProps['columns'] = [
{
field: 'type',
headerName: 'Type',
width: 120,
editable: true,
valueGetter: (value) => {
const typeMap: Record<string, string> = {
folder: 'Folder',
tsx: 'TypeScript',
ts: 'TypeScript',
json: 'JSON',
md: 'Markdown',
css: 'CSS',
svg: 'SVG Image',
png: 'PNG Image',
jpg: 'JPEG Image',
txt: 'Text',
};
return typeMap[value] || value;
},
},
{
field: 'modified',
headerName: 'Modified',
editable: true,
width: 140,
type: 'date',
valueFormatter: (value) => {
if (!value) {
return '';
}
const date = new Date(value);
return date.toLocaleDateString('en-US', {
month: 'short',
day: 'numeric',
year: 'numeric',
});
},
},
{ field: 'size', headerName: 'Size', width: 100, editable: true },
];
const isValidRowReorder: DataGridProProps['isValidRowReorder'] = (context) => {
const targetRow = context.apiRef.current.getRow(context.targetNode.id);
if (
!targetRow ||
(targetRow.type.toLowerCase() !== 'folder' && context.dropPosition === 'inside')
) {
return false;
}
return true;
};
const getTreeDataPath: DataGridProProps['getTreeDataPath'] = (row) => {
return row.path;
};
const setTreeDataPath: DataGridProProps['setTreeDataPath'] = (path, row) => {
return {
...row,
path,
};
};
const groupingColDef: DataGridProProps['groupingColDef'] = {
headerName: 'Name',
renderCell: TreeDataSyncRowDataGroupingCell as any,
};
:::info
위 데모는 isValidRowReorder() prop을 사용하여 파일(또는 리프 행)을 부모로 변환하는 것을 금지합니다.
자세한 내용은 Row ordering—Disable specific reorder operations 문서 섹션을 참고하세요. :::
트리 데이터 자식 지연 로딩
트리 데이터 자식의 지연 로딩에 대한 자세한 내용은 Server-side data—Tree data를 참고하세요.