Data Grid - 열 그룹(Column groups)
열을 그룹화합니다.
본문
열을 그룹화하면 헤더에 다중 레벨 계층 구조의 열을 가질 수 있습니다.
열 그룹 정의하기
columnGroupingModel prop으로 열 그룹을 정의할 수 있습니다.
이 prop은 열 그룹의 배열을 받습니다.
열 그룹은 최소 두 가지 속성으로 정의됩니다:
groupId: 그룹을 식별하는 데 사용되는 문자열children: 그룹의 하위 항목을 포함하는 배열
children 속성은 두 가지 유형의 객체를 포함할 수 있습니다:
{ field: string }유형의 리프(leaf) — 해당field를 가진 열을 이 그룹에 추가합니다- 다른 열 그룹 — 중첩 그룹을 만들 수 있게 해줍니다
:::warning 하나의 열은 하나의 그룹에만 연결될 수 있습니다. :::
<DataGrid
columnGroupingModel={[
{
groupId: 'internal data',
children: [{ field: 'id' }],
},
{
groupId: 'character',
children: [
{
groupId: 'naming',
children: [{ field: 'lastName' }, { field: 'firstName' }],
},
{ field: 'age' },
],
},
]}
/>
import { DataGrid, GridColDef, GridColumnGroupingModel } from '@mui/x-data-grid';
const columns: GridColDef[] = [
{ field: 'id', headerName: 'ID', width: 90 },
{
field: 'firstName',
headerName: 'First name',
rowHeader: true,
width: 150,
},
{
field: 'lastName',
headerName: 'Last name',
rowHeader: true,
width: 150,
},
{
field: 'age',
headerName: 'Age',
type: 'number',
width: 110,
},
];
const rows = [
{ id: 1, lastName: 'Snow', firstName: 'Jon', age: 14 },
{ id: 2, lastName: 'Lannister', firstName: 'Cersei', age: 31 },
{ id: 3, lastName: 'Lannister', firstName: 'Jaime', age: 31 },
{ id: 4, lastName: 'Stark', firstName: 'Arya', age: 11 },
{ id: 5, lastName: 'Targaryen', firstName: 'Daenerys', age: null },
{ id: 6, lastName: 'Melisandre', firstName: null, age: 150 },
{ id: 7, lastName: 'Clifford', firstName: 'Ferrara', age: 44 },
{ id: 8, lastName: 'Frances', firstName: 'Rossini', age: 36 },
{ id: 9, lastName: 'Roxie', firstName: 'Harvey', age: 65 },
];
const columnGroupingModel: GridColumnGroupingModel = [
{
groupId: 'Internal',
description: '',
children: [{ field: 'id' }],
},
{
groupId: 'Basic info',
children: [
{
groupId: 'Full name',
children: [{ field: 'lastName' }, { field: 'firstName' }],
},
{ field: 'age' },
],
},
];
export default function BasicGroupingDemo() {
return (
<div style={{ height: 400, width: '100%' }}>
<DataGrid
rows={rows}
columns={columns}
checkboxSelection
disableRowSelectionOnClick
columnGroupingModel={columnGroupingModel}
/>
</div>
);
}
열 그룹 커스터마이즈
필수 속성인 groupId와 children 외에도 다음 선택적 속성을 사용해 열 그룹을 커스터마이즈할 수 있습니다:
headerName: 열의 이름으로 표시되는 문자열(groupId대신).description: 툴팁에 표시할 텍스트.headerClassName: 스타일 커스터마이즈용 CSS 클래스.renderHeaderGroup: 커스텀 React 컴포넌트를 반환하는 함수.
import * as React from 'react';
import { styled } from '@mui/material/styles';
import Box from '@mui/material/Box';
import {
DataGrid,
GridColDef,
GridColumnGroupHeaderParams,
GridColumnGroupingModel,
} from '@mui/x-data-grid';
import BuildIcon from '@mui/icons-material/Build';
import PersonIcon from '@mui/icons-material/Person';
const columns: GridColDef[] = [
{ field: 'id', headerName: 'ID', width: 150 },
{
field: 'firstName',
headerName: 'First name',
rowHeader: true,
width: 150,
},
{
field: 'lastName',
headerName: 'Last name',
rowHeader: true,
width: 150,
},
{
field: 'age',
headerName: 'Age',
type: 'number',
width: 110,
},
];
const rows = [
{ id: 1, lastName: 'Snow', firstName: 'Jon', age: 14 },
{ id: 2, lastName: 'Lannister', firstName: 'Cersei', age: 31 },
{ id: 3, lastName: 'Lannister', firstName: 'Jaime', age: 31 },
{ id: 4, lastName: 'Stark', firstName: 'Arya', age: 11 },
{ id: 5, lastName: 'Targaryen', firstName: 'Daenerys', age: null },
{ id: 6, lastName: 'Melisandre', firstName: null, age: 150 },
{ id: 7, lastName: 'Clifford', firstName: 'Ferrara', age: 44 },
{ id: 8, lastName: 'Frances', firstName: 'Rossini', age: 36 },
{ id: 9, lastName: 'Roxie', firstName: 'Harvey', age: 65 },
];
interface HeaderWithIconProps extends GridColumnGroupHeaderParams {
icon: React.ReactNode;
}
const HeaderWithIconRoot = styled('div')(({ theme }) => ({
overflow: 'hidden',
display: 'flex',
alignItems: 'center',
'& span': {
overflow: 'hidden',
textOverflow: 'ellipsis',
marginRight: theme.spacing(0.5),
},
}));
function HeaderWithIcon(props: HeaderWithIconProps) {
const { icon, ...params } = props;
return (
<HeaderWithIconRoot>
<span>{params.headerName ?? params.groupId}</span> {icon}
</HeaderWithIconRoot>
);
}
const columnGroupingModel: GridColumnGroupingModel = [
{
groupId: 'internal_data',
headerName: 'Internal',
description: '',
renderHeaderGroup: (params) => (
<HeaderWithIcon {...params} icon={<BuildIcon fontSize="small" />} />
),
children: [{ field: 'id' }],
},
{
groupId: 'character',
description: 'Information about the character',
headerName: 'Basic info',
renderHeaderGroup: (params) => (
<HeaderWithIcon {...params} icon={<PersonIcon fontSize="small" />} />
),
children: [
{
groupId: 'naming',
headerName: 'Names',
headerClassName: 'my-super-theme--naming-group',
children: [{ field: 'lastName' }, { field: 'firstName' }],
},
{ field: 'age' },
],
},
];
export default function CustomizationDemo() {
return (
<Box
sx={{
height: 400,
width: '100%',
'& .my-super-theme--naming-group': {
backgroundColor: 'rgba(255, 7, 0, 0.55)',
},
}}
>
<DataGrid
rows={rows}
columns={columns}
checkboxSelection
disableRowSelectionOnClick
columnGroupingModel={columnGroupingModel}
/>
</Box>
);
}
그룹 헤더 높이
기본적으로 열 그룹 헤더는 열 헤더와 같은 높이입니다. 기본값은 56픽셀이거나 columnHeaderHeight prop으로 설정한 커스텀 값입니다.
columnGroupHeaderHeight prop을 사용해 열 그룹 헤더를 열 헤더와 독립적으로 크기를 조정할 수 있습니다.
import { DataGrid, GridColDef, GridColumnGroupingModel } from '@mui/x-data-grid';
const columns: GridColDef[] = [
{ field: 'id', headerName: 'ID', width: 90 },
{
field: 'firstName',
headerName: 'First name',
rowHeader: true,
width: 150,
},
{
field: 'lastName',
headerName: 'Last name',
rowHeader: true,
width: 150,
},
{
field: 'age',
headerName: 'Age',
type: 'number',
width: 110,
},
];
const rows = [
{ id: 1, lastName: 'Snow', firstName: 'Jon', age: 14 },
{ id: 2, lastName: 'Lannister', firstName: 'Cersei', age: 31 },
{ id: 3, lastName: 'Lannister', firstName: 'Jaime', age: 31 },
{ id: 4, lastName: 'Stark', firstName: 'Arya', age: 11 },
{ id: 5, lastName: 'Targaryen', firstName: 'Daenerys', age: null },
{ id: 6, lastName: 'Melisandre', firstName: null, age: 150 },
{ id: 7, lastName: 'Clifford', firstName: 'Ferrara', age: 44 },
{ id: 8, lastName: 'Frances', firstName: 'Rossini', age: 36 },
{ id: 9, lastName: 'Roxie', firstName: 'Harvey', age: 65 },
];
const columnGroupingModel: GridColumnGroupingModel = [
{
groupId: 'Internal',
description: '',
children: [{ field: 'id' }],
},
{
groupId: 'Basic info',
children: [
{
groupId: 'Full name',
children: [{ field: 'lastName' }, { field: 'firstName' }],
},
{ field: 'age' },
],
},
];
export default function GroupHeaderHeight() {
return (
<div style={{ height: 400, width: '100%' }}>
<DataGrid
rows={rows}
columns={columns}
columnGroupingModel={columnGroupingModel}
columnGroupHeaderHeight={36}
/>
</div>
);
}
열 재정렬
기본적으로 그룹에 속한 열은 그룹 밖으로 드래그할 수 없습니다.
열 그룹 객체에서 freeReordering: true를 설정해 특정 그룹에서 이 동작을 커스터마이즈할 수 있습니다.
아래 예시에서는 Full name 열 그룹만 분할할 수 있고, 다른 열 그룹은 분할할 수 없습니다.
import {
DataGridPro,
GridColDef,
GridColumnGroupingModel,
} from '@mui/x-data-grid-pro';
const columns: GridColDef[] = [
{ field: 'id', headerName: 'ID', width: 100 },
{ field: 'isAdmin', type: 'boolean', headerName: 'is admin', width: 100 },
{
field: 'firstName',
headerName: 'First name',
rowHeader: true,
width: 150,
},
{
field: 'lastName',
headerName: 'Last name',
rowHeader: true,
width: 150,
},
{
field: 'age',
headerName: 'Age',
type: 'number',
width: 110,
},
];
const rows = [
{ id: 1, isAdmin: false, lastName: 'Snow', firstName: 'Jon', age: 14 },
{ id: 2, isAdmin: true, lastName: 'Lannister', firstName: 'Cersei', age: 31 },
{ id: 3, isAdmin: false, lastName: 'Lannister', firstName: 'Jaime', age: 31 },
{ id: 4, isAdmin: false, lastName: 'Stark', firstName: 'Arya', age: 11 },
{ id: 5, isAdmin: true, lastName: 'Targaryen', firstName: 'Daenerys', age: null },
{ id: 6, isAdmin: true, lastName: 'Melisandre', firstName: null, age: 150 },
{ id: 7, isAdmin: false, lastName: 'Clifford', firstName: 'Ferrara', age: 44 },
{ id: 8, isAdmin: false, lastName: 'Frances', firstName: 'Rossini', age: 36 },
{ id: 9, isAdmin: false, lastName: 'Roxie', firstName: 'Harvey', age: 65 },
];
const columnGroupingModel: GridColumnGroupingModel = [
{
groupId: 'internal_data',
headerName: 'Internal (not freeReordering)',
description: '',
children: [{ field: 'id' }, { field: 'isAdmin' }],
},
{
groupId: 'naming',
headerName: 'Full name (freeReordering)',
freeReordering: true,
children: [{ field: 'lastName' }, { field: 'firstName' }],
},
];
export default function BreakingGroupDemo() {
return (
<div style={{ height: 400, width: '100%' }}>
<DataGridPro
rows={rows}
columns={columns}
checkboxSelection
disableRowSelectionOnClick
columnGroupingModel={columnGroupingModel}
/>
</div>
);
}
접을 수 있는 열 그룹
아래 데모는 renderHeaderGroup을 사용해 열 그룹을 접고 펼치는 버튼을 추가합니다.
import { styled } from '@mui/material/styles';
import Box from '@mui/material/Box';
import IconButton from '@mui/material/IconButton';
import {
DataGrid,
GridColDef,
GridColumnGroupHeaderParams,
GridColumnGroupingModel,
gridColumnVisibilityModelSelector,
useGridApiContext,
} from '@mui/x-data-grid';
import KeyboardArrowRightIcon from '@mui/icons-material/KeyboardArrowRight';
import KeyboardArrowDownIcon from '@mui/icons-material/KeyboardArrowDown';
const COLLAPSIBLE_COLUMN_GROUPS: Record<string, Array<string>> = {
character: ['lastName', 'age'],
naming: ['lastName'],
};
const ColumnGroupRoot = styled('div')({
overflow: 'hidden',
display: 'flex',
alignItems: 'center',
});
const ColumnGroupTitle = styled('span')({
overflow: 'hidden',
textOverflow: 'ellipsis',
});
function CollapsibleHeaderGroup({
groupId,
headerName,
}: GridColumnGroupHeaderParams) {
const apiRef = useGridApiContext();
const columnVisibilityModel = gridColumnVisibilityModelSelector(apiRef);
if (!groupId) {
return null;
}
const isCollapsible = Boolean(COLLAPSIBLE_COLUMN_GROUPS[groupId]);
const isGroupCollapsed = COLLAPSIBLE_COLUMN_GROUPS[groupId].every(
(field) => columnVisibilityModel[field] === false,
);
return (
<ColumnGroupRoot>
<ColumnGroupTitle>{headerName ?? groupId}</ColumnGroupTitle>{' '}
{isCollapsible && (
<IconButton
sx={{ ml: 0.5 }}
onClick={() => {
const newModel = { ...columnVisibilityModel };
COLLAPSIBLE_COLUMN_GROUPS[groupId].forEach((field) => {
newModel[field] = !!isGroupCollapsed;
});
apiRef.current.setColumnVisibilityModel(newModel);
}}
>
{isGroupCollapsed ? (
<KeyboardArrowRightIcon fontSize="small" />
) : (
<KeyboardArrowDownIcon fontSize="small" />
)}
</IconButton>
)}
</ColumnGroupRoot>
);
}
const columnGroupingModel: GridColumnGroupingModel = [
{
groupId: 'Internal',
description: '',
children: [{ field: 'id' }],
},
{
groupId: 'character',
description: 'Information about the character',
headerName: 'Basic info',
renderHeaderGroup: (params) => {
return <CollapsibleHeaderGroup {...params} />;
},
children: [
{
groupId: 'naming',
headerName: 'Names',
renderHeaderGroup: (params) => <CollapsibleHeaderGroup {...params} />,
children: [{ field: 'lastName' }, { field: 'firstName' }],
},
{ field: 'age' },
],
},
];
const columns: GridColDef[] = [
{ field: 'id', headerName: 'ID', width: 150 },
{ field: 'firstName', headerName: 'First name', width: 150, rowHeader: true },
{ field: 'lastName', headerName: 'Last name', width: 150, rowHeader: true },
{ field: 'age', headerName: 'Age', type: 'number', width: 110 },
];
const rows = [
{ id: 1, lastName: 'Snow', firstName: 'Jon', age: 35 },
{ id: 2, lastName: 'Lannister', firstName: 'Cersei', age: 42 },
{ id: 3, lastName: 'Lannister', firstName: 'Jaime', age: 45 },
{ id: 4, lastName: 'Stark', firstName: 'Arya', age: 16 },
{ id: 5, lastName: 'Targaryen', firstName: 'Daenerys', age: null },
{ id: 6, lastName: 'Melisandre', firstName: null, age: 150 },
{ id: 7, lastName: 'Clifford', firstName: 'Ferrara', age: 44 },
{ id: 8, lastName: 'Frances', firstName: 'Rossini', age: 36 },
{ id: 9, lastName: 'Roxie', firstName: 'Harvey', age: 65 },
];
export default function CollapsibleColumnGroups() {
return (
<Box sx={{ height: 400, width: '100%' }}>
<DataGrid
rows={rows}
columns={columns}
checkboxSelection
disableRowSelectionOnClick
columnGroupingModel={columnGroupingModel}
/>
</Box>
);
}
그룹 가시성 관리하기 🚧
:::warning 이 기능은 아직 사용할 수 없지만 계획되어 있습니다 — 이 GitHub 이슈에 👍로 투표해 우선순위를 높이는 데 도움을 주세요. 특히 해결해야 할 사용 사례가 있거나 현재 솔루션에서 특정 문제를 겪고 있다면, 요구 사항을 설명하는 댓글을 남겨 주세요. :::
이 기능을 사용하면 사용자가 그룹화된 열을 펼치고 접어 가시성을 토글할 수 있게 됩니다.
열 그룹 순서 🚧
:::warning 이 기능은 아직 사용할 수 없지만 계획되어 있습니다 — 이 GitHub 이슈에 👍로 투표해 우선순위를 높이는 데 도움을 주세요. 특히 해결해야 할 사용 사례가 있거나 현재 솔루션에서 특정 문제를 겪고 있다면, 요구 사항을 설명하는 댓글을 남겨 주세요. :::
이 기능을 사용하면 사용자가 그룹화된 헤더를 드래그 앤 드롭해 그룹화된 모든 하위 항목을 한 번에 이동할 수 있게 됩니다(일반 열에서는 이미 가능).