Data Grid - 행 그룹화 레시피
Data Grid - 행 그룹화 레시피 (Row grouping recipes)
고급 그리드 커스터마이즈 레시피들을 알아봅시다.
본문
행 클릭으로 그룹 토글하기 (Toggling groups on row click)
아래 데모에서는 그룹 행의 아무 곳이나 클릭해 그룹을 토글할 수 있어요.
import * as React from 'react';
import {
DataGridPremium,
useGridApiRef,
useKeepGroupedColumnsHidden,
GridEventListener,
} from '@mui/x-data-grid-premium';
import { useMovieData } from '@mui/x-data-grid-generator';
export default function RowGroupingExpandOnRowClick() {
const data = useMovieData();
const apiRef = useGridApiRef();
const initialState = useKeepGroupedColumnsHidden({
apiRef,
initialState: {
rowGrouping: {
model: ['company'],
},
},
});
const onRowClick = React.useCallback<GridEventListener<'rowClick'>>(
(params) => {
const rowNode = apiRef.current?.getRowNode(params.id);
if (rowNode && rowNode.type === 'group') {
apiRef.current?.setRowChildrenExpansion(
params.id,
!rowNode.childrenExpanded,
);
}
},
[apiRef],
);
return (
<div style={{ height: 400, width: '100%' }}>
<DataGridPremium
{...data}
apiRef={apiRef}
initialState={initialState}
onRowClick={onRowClick}
/>
</div>
);
}
그룹화된 컬럼 고정하기 (Pinning a grouped column)
GRID_ROW_GROUPING_SINGLE_GROUPING_FIELD를 사용해 그룹화된 컬럼을 고정할 수 있어요. 아래 데모에서 Company 컬럼이 고정되어 있습니다.
import {
DataGridPremium,
useGridApiRef,
useKeepGroupedColumnsHidden,
GRID_ROW_GROUPING_SINGLE_GROUPING_FIELD,
} from '@mui/x-data-grid-premium';
import { useMovieData } from '@mui/x-data-grid-generator';
export default function RowGroupingPinning() {
const data = useMovieData();
const apiRef = useGridApiRef();
const initialState = useKeepGroupedColumnsHidden({
apiRef,
initialState: {
rowGrouping: {
model: ['company'],
},
pinnedColumns: { left: [GRID_ROW_GROUPING_SINGLE_GROUPING_FIELD] },
},
});
return (
<div style={{ height: 400, width: '100%' }}>
<DataGridPremium {...data} apiRef={apiRef} initialState={initialState} />
</div>
);
}
드래그 앤 드롭으로 그룹 만들고 재정렬하기 (Creating and reordering groups with drag and drop)
드래그 앤 드롭으로 행 그룹을 만들 수 있는 커스텀 툴바를 추가하는 예시는 Toolbar component—Row grouping bar를 참고하세요.
자식 행 수로 행 그룹 정렬하기 (Sorting row groups by the number of child rows)
기본적으로 행 그룹 컬럼은 그룹화 컬럼의 sortComparator를 사용해 정렬합니다.
행 그룹을 자식 행 수로 정렬하려면 groupingColDef.sortComparator를 재정의하세요.
import * as React from 'react';
import {
DataGridPremium,
gridFilteredDescendantCountLookupSelector,
useGridApiRef,
GRID_ROW_GROUPING_SINGLE_GROUPING_FIELD,
GridGroupingColDefOverride,
GridInitialState,
} from '@mui/x-data-grid-premium';
import { useMovieData } from '@mui/x-data-grid-generator';
const initialState: GridInitialState = {
rowGrouping: {
model: ['company', 'cinematicUniverse'],
},
sorting: {
sortModel: [{ field: GRID_ROW_GROUPING_SINGLE_GROUPING_FIELD, sort: 'desc' }],
},
};
export default function RowGroupingSortByChildRows() {
const data = useMovieData();
const apiRef = useGridApiRef();
const groupingColDef: GridGroupingColDefOverride = React.useMemo(
() => ({
width: 275,
sortComparator: (v1, v2, cellParams1, cellParams2) => {
if (
cellParams1.rowNode.type === 'group' &&
cellParams2.rowNode.type === 'group'
) {
// Sort the values, but only within the same group
if (
cellParams1.rowNode.groupingField === cellParams2.rowNode.groupingField
) {
const filteredDescendantCountLookup =
gridFilteredDescendantCountLookupSelector(apiRef);
const cell1DescendantCount =
filteredDescendantCountLookup[cellParams1.rowNode.id] ?? 0;
const cell2DescendantCount =
filteredDescendantCountLookup[cellParams2.rowNode.id] ?? 0;
return cell1DescendantCount - cell2DescendantCount;
}
return 0;
}
if (cellParams1.rowNode.type === 'group') {
return 1;
}
if (cellParams2.rowNode.type === 'group') {
return -1;
}
return 0;
},
}),
[apiRef],
);
return (
<div style={{ height: 400, width: '100%' }}>
<DataGridPremium
{...data}
apiRef={apiRef}
initialState={initialState}
groupingColDef={groupingColDef}
/>
</div>
);
}
푸터에 자식 행 수 표시하기 (Displaying child row count in footer)
기본적으로 푸터의 행 수는 필터링 후 보이는 최상위 레벨 행의 수입니다.
아래 데모에서는 CustomFooterRowCount 컴포넌트가 footerRowCount slot에 추가됩니다. 이 컴포넌트는 gridFilteredDescendantRowCountSelector를 사용해 자식 행 수를 가져오고 그룹 수와 함께 표시해요.
import {
DataGridPremium,
GridRowCountProps,
useGridApiRef,
useGridSelector,
useKeepGroupedColumnsHidden,
useGridApiContext,
gridFilteredDescendantRowCountSelector,
} from '@mui/x-data-grid-premium';
import { useMovieData } from '@mui/x-data-grid-generator';
import Box from '@mui/material/Box';
function CustomFooterRowCount(props: GridRowCountProps) {
const { visibleRowCount: topLevelRowCount } = props;
const apiRef = useGridApiContext();
const descendantRowCount = useGridSelector(
apiRef,
gridFilteredDescendantRowCountSelector,
);
return (
<Box sx={{ mx: 2 }}>
{descendantRowCount} row{descendantRowCount > 1 ? 's' : ''} in{' '}
{topLevelRowCount} group
{topLevelRowCount > 1 ? 's' : ''}
</Box>
);
}
export default function RowGroupingChildRowCount() {
const data = useMovieData();
const apiRef = useGridApiRef();
const initialState = useKeepGroupedColumnsHidden({
apiRef,
initialState: {
rowGrouping: {
model: ['company'],
},
},
});
return (
<div style={{ height: 400, width: '100%' }}>
<DataGridPremium
{...data}
apiRef={apiRef}
initialState={initialState}
slots={{
footerRowCount: CustomFooterRowCount,
}}
/>
</div>
);
}
자식 조건에 따른 행 그룹 스타일링 (Styling row groups based on child conditions)
자세한 내용은 styling row groups 섹션을 참고하세요.
여러 필드를 하나의 컬럼으로 그룹화하기 (Grouping multiple fields into a single column)
구분자 상수와 함께 groupingValueGetter()를 제공해 여러 컬럼을 하나로 결합하고, 출력 인터페이스를 제어하려면 커스텀 renderCell()을 제공하세요.
다음 데모는 여러 그룹화 컬럼(label과 priority)을 하나의 그룹화 컬럼으로 만드는 방법을 보여줘요.
columns 배열의 두 번째 컬럼 정의를 살펴보세요.
field는 그룹화 컬럼 중 하나인label로 설정됩니다.groupingValueGetter는label과priority필드를 구분자 상수로 분리된 단일 문자열로 결합해, 이 컬럼의 그룹화 기준을 효과적으로 변경합니다.renderCell은 행 타입이 그룹일 때 문자열을 분리하고priority필드를 색상이 있는Chip으로 표시합니다.
import Box from '@mui/material/Box';
import {
DataGridPremium,
GridColDef,
useKeepGroupedColumnsHidden,
useGridApiRef,
} from '@mui/x-data-grid-premium';
import Chip, { ChipProps } from '@mui/material/Chip';
const SEPARATOR = '___MULTI_COL___';
const columns: GridColDef<Task>[] = [
{
field: 'assignee',
headerName: 'Assignee',
width: 150,
},
{
field: 'label',
headerName: 'Task Group',
width: 240,
groupingValueGetter: (value, row) => `${value}${SEPARATOR}${row.priority}`,
renderCell: (params) => {
if (params.rowNode.type === 'group') {
if (params.value === undefined) {
return null;
}
const val = params.value.split(SEPARATOR);
let color: ChipProps['color'] = 'default';
if (val[1] === 'High') {
color = 'error';
} else if (val[1] === 'Medium') {
color = 'warning';
} else {
color = 'success';
}
return (
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<div>{val[0]}</div>
<Chip color={color} label={val[1]} size="small" />
</Box>
);
}
return params.value;
},
},
{
field: 'detail',
headerName: 'Detail',
width: 360,
},
];
interface Task {
id: number;
label: string;
detail: string;
assignee: string;
priority: 'Low' | 'Medium' | 'High';
}
const rows: Task[] = [
{
id: 1,
label: 'Design mockups',
detail: 'Create initial wireframes and mockups for the new dashboard',
assignee: 'Alice',
priority: 'High',
},
{
id: 2,
label: 'Design mockups',
detail: 'Design mobile responsive layouts',
assignee: 'Alice',
priority: 'High',
},
{
id: 3,
label: 'Design mockups',
detail: 'Update color scheme and typography',
assignee: 'Alice',
priority: 'Medium',
},
{
id: 4,
label: 'Code review',
detail: 'Review authentication module PR #123',
assignee: 'Bob',
priority: 'High',
},
{
id: 5,
label: 'Code review',
detail: 'Review API endpoint refactoring',
assignee: 'Bob',
priority: 'Medium',
},
{
id: 6,
label: 'Code review',
detail: 'Review database migration scripts',
assignee: 'Bob',
priority: 'Medium',
},
{
id: 7,
label: 'Design mockups',
detail: 'Create icon set for navigation',
assignee: 'Charlie',
priority: 'Low',
},
{
id: 8,
label: 'Code review',
detail: 'Review test coverage improvements',
assignee: 'Charlie',
priority: 'Low',
},
];
export default function RowGroupingMultipleFields() {
const apiRef = useGridApiRef();
const initialState = useKeepGroupedColumnsHidden({
apiRef,
initialState: {
rowGrouping: {
model: ['assignee', 'label'],
},
},
});
return (
<Box sx={{ height: 400, width: '100%' }}>
<DataGridPremium
rows={rows}
columns={columns}
initialState={initialState}
defaultGroupingExpansionDepth={1}
/>
</Box>
);
}