집계(Aggregation)와 행 그룹핑(Row Grouping)으로 Data Grid 만들기
집계 함수와 행 그룹핑을 사용하는 클라이언트 사이드 Data Grid를 step by step으로 직접 만들어보는 튜토리얼이에요. 데이터를 로컬에 정의하고, 그리드로 컬럼 값별 행을 그룹 지으며, 그룹 안의 데이터를 집계 함수로 분석하는 방법을 배워요.
본문
개요
이 튜토리얼은 Data Grid Premium을 사용해 집계 함수와 행 그룹핑을 보여주는 클라이언트 사이드 Data Grid를 만들어가는 과정을 안내해요. 데이터를 로컬에 정의하고, 그리드를 사용해 컬럼 값별로 행을 그룹 지으며, 그룹 안의 데이터를 분석하기 위해 집계 함수(예: sum, average, min, max)를 적용할 거예요.
:::success 튜토리얼 전체를 건너뛰고 싶다면 GitHub에 있는 완성 앱 코드를 확인할 수 있어요. :::
사전 준비
- 기본 React 지식
- TypeScript 인터페이스 이해
관련 문서
MUI X Data Grid가 처음이라면 아래 페이지가 도움이 될 수 있어요:
1부: 앱 설정
1부에서는 Vite로 React 앱을 만들고 Data Grid에 필요한 의존성을 설치할 거예요.
1. 프로젝트 만들기
새 디렉토리를 만들고 Vite로 TypeScript React 앱을 스캐폴딩해요:
mkdir aggregation-row-grouping &&
cd aggregation-row-grouping &&
pnpm create vite@latest . -- --template react-ts &&
pnpm install
2. 의존성 설치
Material UI와 MUI X Data Grid Premium을 설치해요:
pnpm install @mui/material @emotion/react @emotion/styled @mui/icons-material @mui/x-data-grid-premium @fontsource/roboto
:::success 이 튜토리얼은 pnpm을 사용하지만 모든 MUI 라이브러리는 npm과 yarn과도 호환돼요. 자세한 내용은 Material UI 설치 페이지를 참고하세요. :::
3. 앱 셸 설정
components 디렉토리를 만들고 그리드용 플레이스홀더를 추가해요.
src/components/EmployeeDataGrid.tsx를 만드세요:
import * as React from 'react';
import {
DataGridPremium,
type GridColDef,
useGridApiRef,
useKeepGroupedColumnsHidden,
} from '@mui/x-data-grid-premium';
import { Box, Typography } from '@mui/material';
const EmployeeDataGrid = () => {
return (
<Box sx={{ height: 600, width: '100%' }}>
<Typography variant="h4" component="h1" gutterBottom>
MUI X Data Grid Premium - Aggregation & Row Grouping
</Typography>
<Typography variant="body1" color="text.secondary" sx={{ mb: 3 }}>
Row grouping by department and role, with aggregation (sum) on salary and
projects.
</Typography>
</Box>
);
};
export default EmployeeDataGrid;
import에는 useGridApiRef()와 useKeepGroupedColumnsHidden()이 포함돼요. 이들은 행 그룹핑과 집계를 설정할 때인 7단계에서 사용할 거예요.
src/App.tsx를 업데이트해요:
import * as React from 'react';
import CssBaseline from '@mui/material/CssBaseline';
import { Container } from '@mui/material';
import EmployeeDataGrid from './components/EmployeeDataGrid';
function App() {
return (
<React.Fragment>
<CssBaseline />
<Container maxWidth="lg" sx={{ py: 4 }}>
<EmployeeDataGrid />
</Container>
</React.Fragment>
);
}
export default App;
src/main.tsx의 내용을 다음으로 교체해요:
import * as React from 'react';
import * as ReactDOM from 'react-dom/client';
import App from './App';
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<App />
</React.StrictMode>,
);
4. 앱 실행
pnpm dev
앱은 http://localhost:5173에서 실행돼요.
2부: 집계와 행 그룹핑이 있는 Data Grid
이 섹션에서는 EmployeeDataGrid.tsx에 로컬 데이터, 컬럼 정의, 행 그룹핑, 집계를 추가할 거예요.
5. 데이터 구조와 행 정의
Employee 인터페이스와 로컬 행 배열을 정의해요.
EmployeeDataGrid.tsx에서 import 아래에 추가하세요:
interface Employee {
id: number;
name: string;
email: string;
role: string;
department: string;
salary: number;
startDate: string;
projects: number;
}
const EMPLOYEE_DATA: Employee[] = [
{
id: 1,
name: 'John Doe',
email: 'john@example.com',
role: 'Developer',
department: 'Engineering',
salary: 75000,
startDate: '2023-01-15',
projects: 5,
},
{
id: 2,
name: 'Jane Smith',
email: 'jane@example.com',
role: 'Designer',
department: 'Design',
salary: 65000,
startDate: '2023-02-20',
projects: 3,
},
{
id: 3,
name: 'Bob Johnson',
email: 'bob@example.com',
role: 'Manager',
department: 'Product',
salary: 85000,
startDate: '2022-11-10',
projects: 8,
},
{
id: 4,
name: 'Alice Brown',
email: 'alice@example.com',
role: 'Developer',
department: 'Engineering',
salary: 80000,
startDate: '2023-03-05',
projects: 6,
},
{
id: 5,
name: 'Charlie Wilson',
email: 'charlie@example.com',
role: 'Analyst',
department: 'Data',
salary: 70000,
startDate: '2023-04-12',
projects: 4,
},
{
id: 6,
name: 'Diana Davis',
email: 'diana@example.com',
role: 'Designer',
department: 'Design',
salary: 68000,
startDate: '2023-01-30',
projects: 2,
},
{
id: 7,
name: 'Eve Miller',
email: 'eve@example.com',
role: 'Developer',
department: 'Engineering',
salary: 82000,
startDate: '2022-12-18',
projects: 7,
},
{
id: 8,
name: 'Frank Garcia',
email: 'frank@example.com',
role: 'Manager',
department: 'Sales',
salary: 90000,
startDate: '2022-09-25',
projects: 10,
},
{
id: 9,
name: 'Grace Lee',
email: 'grace@example.com',
role: 'Analyst',
department: 'Data',
salary: 72000,
startDate: '2023-05-08',
projects: 5,
},
{
id: 10,
name: 'Henry Taylor',
email: 'henry@example.com',
role: 'Developer',
department: 'Engineering',
salary: 78000,
startDate: '2023-06-14',
projects: 4,
},
{
id: 11,
name: 'Ivy Chen',
email: 'ivy@example.com',
role: 'Developer',
department: 'Engineering',
salary: 76000,
startDate: '2023-07-22',
projects: 6,
},
{
id: 12,
name: 'Jack Anderson',
email: 'jack@example.com',
role: 'Designer',
department: 'Design',
salary: 67000,
startDate: '2023-08-15',
projects: 3,
},
{
id: 13,
name: 'Kate Martinez',
email: 'kate@example.com',
role: 'Manager',
department: 'Marketing',
salary: 88000,
startDate: '2023-09-03',
projects: 9,
},
{
id: 14,
name: 'Liam Thompson',
email: 'liam@example.com',
role: 'Analyst',
department: 'Data',
salary: 71000,
startDate: '2023-10-11',
projects: 4,
},
{
id: 15,
name: 'Maya Rodriguez',
email: 'maya@example.com',
role: 'Developer',
department: 'Engineering',
salary: 79000,
startDate: '2023-11-28',
projects: 5,
},
{
id: 16,
name: 'Noah White',
email: 'noah@example.com',
role: 'Designer',
department: 'Design',
salary: 66000,
startDate: '2023-12-05',
projects: 2,
},
{
id: 17,
name: 'Olivia Harris',
email: 'olivia@example.com',
role: 'Manager',
department: 'HR',
salary: 87000,
startDate: '2024-01-14',
projects: 7,
},
{
id: 18,
name: 'Paul Clark',
email: 'paul@example.com',
role: 'Analyst',
department: 'Data',
salary: 73000,
startDate: '2024-02-20',
projects: 6,
},
{
id: 19,
name: 'Quinn Lewis',
email: 'quinn@example.com',
role: 'Developer',
department: 'Engineering',
salary: 81000,
startDate: '2024-03-08',
projects: 8,
},
{
id: 20,
name: 'Ruby Hall',
email: 'ruby@example.com',
role: 'Designer',
department: 'Design',
salary: 69000,
startDate: '2024-04-12',
projects: 4,
},
{
id: 21,
name: 'Sam Young',
email: 'sam@example.com',
role: 'Manager',
department: 'Finance',
salary: 92000,
startDate: '2024-05-18',
projects: 11,
},
{
id: 22,
name: 'Tara King',
email: 'tara@example.com',
role: 'Analyst',
department: 'Data',
salary: 74000,
startDate: '2024-06-25',
projects: 5,
},
{
id: 23,
name: 'Uma Patel',
email: 'uma@example.com',
role: 'Developer',
department: 'Engineering',
salary: 77000,
startDate: '2024-07-30',
projects: 4,
},
{
id: 24,
name: 'Victor Moore',
email: 'victor@example.com',
role: 'Designer',
department: 'Design',
salary: 64000,
startDate: '2024-08-14',
projects: 3,
},
{
id: 25,
name: 'Wendy Scott',
email: 'wendy@example.com',
role: 'Manager',
department: 'Operations',
salary: 86000,
startDate: '2024-09-22',
projects: 8,
},
{
id: 26,
name: 'Xander Green',
email: 'xander@example.com',
role: 'Analyst',
department: 'Data',
salary: 75000,
startDate: '2024-10-05',
projects: 6,
},
{
id: 27,
name: 'Yara Adams',
email: 'yara@example.com',
role: 'Developer',
department: 'Engineering',
salary: 80000,
startDate: '2024-11-12',
projects: 7,
},
{
id: 28,
name: 'Zane Baker',
email: 'zane@example.com',
role: 'Designer',
department: 'Design',
salary: 67000,
startDate: '2024-12-18',
projects: 2,
},
{
id: 29,
name: 'Aria Nelson',
email: 'aria@example.com',
role: 'Manager',
department: 'Legal',
salary: 95000,
startDate: '2025-01-25',
projects: 6,
},
{
id: 30,
name: 'Blake Carter',
email: 'blake@example.com',
role: 'Analyst',
department: 'Data',
salary: 72000,
startDate: '2025-02-28',
projects: 5,
},
{
id: 31,
name: 'Cora Mitchell',
email: 'cora@example.com',
role: 'Developer',
department: 'Engineering',
salary: 78000,
startDate: '2025-03-15',
projects: 5,
},
{
id: 32,
name: 'Dexter Perez',
email: 'dexter@example.com',
role: 'Designer',
department: 'Design',
salary: 65000,
startDate: '2025-04-20',
projects: 3,
},
{
id: 33,
name: 'Echo Roberts',
email: 'echo@example.com',
role: 'Manager',
department: 'Sales',
salary: 89000,
startDate: '2025-05-10',
projects: 9,
},
{
id: 34,
name: 'Finn Turner',
email: 'finn@example.com',
role: 'Analyst',
department: 'Data',
salary: 71000,
startDate: '2025-06-18',
projects: 4,
},
{
id: 35,
name: 'Gemma Phillips',
email: 'gemma@example.com',
role: 'Developer',
department: 'Engineering',
salary: 82000,
startDate: '2025-07-25',
projects: 6,
},
{
id: 36,
name: 'Hawk Campbell',
email: 'hawk@example.com',
role: 'Designer',
department: 'Design',
salary: 68000,
startDate: '2025-08-30',
projects: 4,
},
{
id: 37,
name: 'Indigo Parker',
email: 'indigo@example.com',
role: 'Manager',
department: 'Product',
salary: 87000,
startDate: '2025-09-05',
projects: 10,
},
{
id: 38,
name: 'Jasper Evans',
email: 'jasper@example.com',
role: 'Analyst',
department: 'Data',
salary: 73000,
startDate: '2025-10-12',
projects: 5,
},
{
id: 39,
name: 'Kai Edwards',
email: 'kai@example.com',
role: 'Developer',
department: 'Engineering',
salary: 79000,
startDate: '2025-11-20',
projects: 7,
},
{
id: 40,
name: 'Luna Collins',
email: 'luna@example.com',
role: 'Designer',
department: 'Design',
salary: 66000,
startDate: '2025-12-28',
projects: 3,
},
];
여기서 일어나는 일:
Employee는 그리드의 한 행을 설명해요.projects와salary필드는 집계에 사용될 거예요.EMPLOYEE_DATA는 인메모리 데이터셋이에요. 그리드는 이 행들을 클라이언트에서 그룹핑하고 집계할 거예요.
6. 그리드 컬럼 정의
데이터와 일치하는 컬럼 정의를 추가해요:
const columns: GridColDef[] = [
{ field: 'id', headerName: 'ID', width: 80 },
{ field: 'name', headerName: 'Name', width: 200 },
{ field: 'email', headerName: 'Email', width: 250 },
{ field: 'role', headerName: 'Role', width: 150 },
{ field: 'department', headerName: 'Department', width: 150 },
{
field: 'salary',
headerName: 'Salary',
width: 120,
type: 'number',
valueFormatter: (value) => `$${value?.toLocaleString()}`,
},
{ field: 'startDate', headerName: 'Start Date', width: 130 },
{ field: 'projects', headerName: 'Projects', width: 120, type: 'number' },
];
여기서 일어나는 일:
field는Employee의 속성과 일치해요.salary와projects의type: 'number'는 그리드가 집계를 적용하게 해줘요.valueFormatter는 급여를 통화로 포맷해요.
7. 행 그룹핑과 집계 구성하기
useGridApiRef()와 useKeepGroupedColumnsHidden()을 사용해 초기 행 그룹핑과 집계를 설정해요:
function EmployeeDataGrid() {
const apiRef = useGridApiRef();
const initialState = useKeepGroupedColumnsHidden({
apiRef,
initialState: {
rowGrouping: {
model: ['department', 'role'],
},
aggregation: {
model: {
salary: 'sum',
projects: 'sum',
},
},
},
});
return (
// ... JSX next
);
}
여기서 일어나는 일:
useKeepGroupedColumnsHidden()이initialState를 감싸, 행 그룹핑 모델에 있는 컬럼(여기서는department와role)이 그리드 본문에서 숨겨지게 해요. 그룹 헤더로만 나타나요. 없으면 그 컬럼들이 일반 데이터 컬럼으로 계속 표시돼요. 이 훅은 사용자가 그룹핑을 변경할 때 컬럼 패널을 동기화해요.apiRef로rowGroupingModelChange를 구독한 뒤setColumnVisibilityModel()을 호출해 컬럼이 그룹핑 모델에 추가/제거될 때 숨기거나 보여줘요.rowGrouping.model은department로, 그리고 각 부서 안에서role로 행을 그룹핑해요.aggregation.model은 각 그룹의salary와projects컬럼에sum집계를 적용해요.
8. 집계 위치 구성
집계된 값이 어디에 나타날지 제어해요:
getAggregationPosition={(groupNode) =>
groupNode.depth === -1 ? 'footer' : 'inline'
}
여기서 일어나는 일:
- 루트 레벨(
depth === -1): 푸터 행에 집계. - 중첩 그룹: 그룹 헤더와 함께 인라인으로 집계.
9. Data Grid Premium 렌더링
rows, columns, 그리고 정의한 옵션으로 그리드를 렌더링해요:
<DataGridPremium
apiRef={apiRef}
rows={EMPLOYEE_DATA}
columns={columns}
initialState={initialState}
pagination
pageSizeOptions={[10, 25, 50, 100]}
disableRowSelectionOnClick
getAggregationPosition={(groupNode) =>
groupNode.depth === -1 ? 'footer' : 'inline'
}
/>
여기서 일어나는 일:
- 행 그룹핑과 집계에는
DataGridPremium이 필요해요. rows={EMPLOYEE_DATA}가 로컬 데이터를 전달해요.initialState가 그룹핑과 집계 구성을 담아요.getAggregationPosition은 집계가 어디(푸터 vs 인라인)에 표시될지 설정해요.
10. 완성된 컴포넌트
5단계와 6단계의 EMPLOYEE_DATA와 columns가 준비되면, EmployeeDataGrid.tsx의 나머지는 다음과 같아요:
function EmployeeDataGrid() {
const apiRef = useGridApiRef();
const initialState = useKeepGroupedColumnsHidden({
apiRef,
initialState: {
rowGrouping: { model: ['department', 'role'] },
aggregation: { model: { salary: 'sum', projects: 'sum' } },
},
});
return (
<Box sx={{ height: 600, width: '100%' }}>
<Typography variant="h4" component="h1" gutterBottom>
MUI X Data Grid Premium - Aggregation & Row Grouping
</Typography>
<Typography variant="body1" color="text.secondary" sx={{ mb: 3 }}>
Row grouping by department and role, with aggregation (sum) on salary and
projects.
</Typography>
<DataGridPremium
apiRef={apiRef}
rows={EMPLOYEE_DATA}
columns={columns}
initialState={initialState}
pagination
pageSizeOptions={[10, 25, 50, 100]}
disableRowSelectionOnClick
getAggregationPosition={(groupNode) =>
groupNode.depth === -1 ? 'footer' : 'inline'
}
/>
</Box>
);
}
export default EmployeeDataGrid;
부서와 역할별로 그룹핑된 직원 데이터가 각 그룹의 급여·프로젝트 합계와 함께 표시되는 것을 볼 수 있어요. 그룹을 펼치고 접어 계층 구조를 탐색해보세요.
집계와 행 그룹핑 이해하기
행 그룹핑
행은 컬럼 값별로 그룹핑돼요. 여기서는 다음을 사용해요:
- Department(부서) – 최상위 그룹
- Role(역할) – 각 부서 안의 하위 그룹
그룹을 펼치거나 접어 상세 행을 볼 수 있어요.
집계 함수
집계는 그룹의 값을 요약해요. 일반적인 함수:
sum– 값의 합avg– 평균min/max– 최솟값 또는 최댓값size– 행 수
이 튜토리얼은 급여와 프로젝트에 sum을 사용해요.
집계 위치
getAggregationPosition은 집계가 어디에 나타날지 제어해요:
'footer'– 푸터 행(루트 레벨)'inline'– 그룹 헤더 옆(중첩 그룹)null– 해당 레벨의 집계 숨기기