본문으로 건너뛰기Skip to content
예제 첫화면Examples home

줄을 묶고 합계 보기: 지역 → 채널Group rows and see totals: region, then channel

같은 값끼리 줄을 묶으면 묶음 줄에 합계가 나와요. 묶는 순서를 바꾸고, 몇 단계까지 열지 고르고, 그룹 체크박스로 한 번에 고를 수 있어요.Rows with the same value gather under a group row with totals. Change the grouping order, choose how many levels are open, and tick a group to select all its rows.

입문Beginner
직접 써 보기Live preview줄을 묶고 합계 보기: 지역 → 채널Group rows and see totals: region, then channel

코드Code

탭을 골라 코드를 복사하세요. 위 화면은 이 코드를 그대로 실행한 결과예요.Pick a tab and copy the code. The preview above runs exactly this code.

이 화면은 새 모양 옵션을 켠 모양이에요: density: 'spacious', iconStyle: 'soft', motion: true (코드에 없으면 기본 모양으로 보여요)This preview has the new-look options on: density: 'spacious', iconStyle: 'soft', motion: true (without them in your code you get the default look)

빌드 도구(Vite 등)를 쓰는 프로젝트용 모듈 파일이에요. 설치 없이 바로 돌려 보려면 HTML 탭이나 직접 해보기를 쓰세요.

버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.

index.html
<div id="app">
  <div class="toolbar">
    <select aria-label="묶는 기준" id="by">
      <option value="region" selected>지역</option>
      <option value="regionChannel">지역 → 채널</option>
      <option value="channelRegion">채널 → 지역</option>
      <option value="none">묶지 않기</option>
    </select>
    <select aria-label="펼침 단계" id="level">
      <option value="0" selected>모두 접기</option>
      <option value="1">1단계까지</option>
      <option value="2">2단계까지</option>
    </select>
    <button type="button" id="expandAll">모두 펼치기</button>
    <button type="button" id="collapseAll">모두 접기</button>
  </div>
  <div id="grid" style="height: 300px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('by').addEventListener('change', (event) => actions.by(api, event.target.value));
document.getElementById('level').addEventListener('change', (event) => actions.level(api, event.target.value));
document.getElementById('expandAll').addEventListener('click', () => actions.expandAll(api));
document.getElementById('collapseAll').addEventListener('click', () => actions.collapseAll(api));
example.js
const regions = ['서울', '경기', '부산', '대전'];
const channels = ['온라인', '매장'];
const products = ['노트북', '모니터', '키보드'];
const rows = Array.from({ length: 24 }, (_, i) => ({
  id: i + 1,
  region: regions[i % 4],
  channel: channels[Math.floor(i / 4) % 2],
  product: products[i % 3],
  qty: 1 + ((i * 5) % 9),
  amount: 180000 + (i % 5) * 120000 + ((i * 37) % 9) * 11000,
}));
// grouping.by의 순서가 단계의 순서예요. expandDepth: 0이면 처음에 모두 접혀 있고, 1이면 맨 위 단계가 열려요.
// 그룹 줄에는 컬럼의 aggregate로 정한 합계가 보이고, summary: true면 맨 아래에 총계 줄이 붙어요.
export const options = {
  columns: [
    { id: 'region', title: '지역', width: 110 },
    { id: 'channel', title: '채널', width: 90 },
    { id: 'product', title: '제품', width: 90 },
    { id: 'qty', title: '수량', kind: 'number', width: 80, align: 'end', aggregate: 'sum' },
    {
      id: 'amount',
      title: '매출(원)',
      kind: 'number',
      width: 130,
      align: 'end',
      aggregate: 'sum',
      formatValue: (v) => Number(v).toLocaleString('ko-KR'),
    },
  ],
  rows,
  rowKey: 'id',
  grouping: { by: ['region'], expandDepth: 0 },
  summary: true,
  selection: { mode: 'multiple', checkbox: true },
};
const titles = { region: '지역', channel: '채널' };
const orders = {
  region: ['region'],
  regionChannel: ['region', 'channel'],
  channelRegion: ['channel', 'region'],
  none: [],
};
let say = () => { };
export function setup(api, log) {
  say = log;
  const off = [
    api.on('groupingChanged', ({ groupBy }) => log({
      ko: groupBy.length
        ? `묶는 순서: ${groupBy.map((id) => titles[id] ?? id).join(' → ')}`
        : '묶지 않았어요.',
      en: groupBy.length
        ? `Grouping order: ${groupBy.map((id) => titles[id] ?? id).join(' → ')}`
        : 'Not grouped.',
    })),
    api.on('selectionChanged', ({ selectedKeys }) => log({
      ko: `${selectedKeys.length}줄을 골랐어요.`,
      en: `${selectedKeys.length} rows selected.`,
    })),
  ];
  return () => off.forEach((fn) => fn());
}
function setLevel(value) {
  const box = document.getElementById('level');
  if (box instanceof HTMLSelectElement)
    box.value = value;
}
export const actions = {
  by: (api, value) => api.setGroupBy(orders[value ?? 'region'] ?? []),
  level: (api, value) => {
    const depth = Number(value ?? '1');
    api.expandToDepth(depth);
    say({
      ko: depth === 0 ? '모두 접었어요.' : `${depth}단계까지 펼쳤어요.`,
      en: depth === 0 ? 'Collapsed all.' : `Expanded to level ${depth}.`,
    });
  },
  expandAll: (api) => {
    api.expandAll();
    setLevel('2'); // 펼침 단계 선택 상자도 지금 상태에 맞춰요
  },
  collapseAll: (api) => {
    api.collapseAll();
    setLevel('0');
  },
};

Module files for a project with a bundler such as Vite. To run it with no setup, use the HTML tab or Try it.

When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.

index.html
<div id="app">
  <div class="toolbar">
    <select aria-label="Group by" id="by">
      <option value="region" selected>Region</option>
      <option value="regionChannel">Region → channel</option>
      <option value="channelRegion">Channel → region</option>
      <option value="none">No grouping</option>
    </select>
    <select aria-label="Open levels" id="level">
      <option value="0" selected>All closed</option>
      <option value="1">Up to level 1</option>
      <option value="2">Up to level 2</option>
    </select>
    <button type="button" id="expandAll">Expand all</button>
    <button type="button" id="collapseAll">Collapse all</button>
  </div>
  <div id="grid" style="height: 300px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('by').addEventListener('change', (event) => actions.by(api, event.target.value));
document.getElementById('level').addEventListener('change', (event) => actions.level(api, event.target.value));
document.getElementById('expandAll').addEventListener('click', () => actions.expandAll(api));
document.getElementById('collapseAll').addEventListener('click', () => actions.collapseAll(api));
example.js
const regions = ['New York', 'Boston', 'Austin', 'Seattle'];
const channels = ['Online', 'In store'];
const products = ['Laptop', 'Monitor', 'Keyboard'];
const rows = Array.from({ length: 24 }, (_, i) => ({
  id: i + 1,
  region: regions[i % 4],
  channel: channels[Math.floor(i / 4) % 2],
  product: products[i % 3],
  qty: 1 + ((i * 5) % 9),
  amount: 180 + (i % 5) * 120 + ((i * 37) % 9) * 11,
}));
// The order of grouping.by is the order of the levels. expandDepth: 0 starts fully collapsed, 1 opens the top level.
// Group rows show the totals set by each column's aggregate, and summary: true adds a total row at the bottom.
export const options = {
  columns: [
    { id: 'region', title: 'Region', width: 110 },
    { id: 'channel', title: 'Channel', width: 110 },
    { id: 'product', title: 'Product', width: 100 },
    { id: 'qty', title: 'Qty', kind: 'number', width: 80, align: 'end', aggregate: 'sum' },
    {
      id: 'amount',
      title: 'Revenue ($)',
      kind: 'number',
      width: 130,
      align: 'end',
      aggregate: 'sum',
      formatValue: (v) => Number(v).toLocaleString('en-US'),
    },
  ],
  rows,
  rowKey: 'id',
  grouping: { by: ['region'], expandDepth: 0 },
  summary: true,
  selection: { mode: 'multiple', checkbox: true },
};
const titles = { region: 'Region', channel: 'Channel' };
const orders = {
  region: ['region'],
  regionChannel: ['region', 'channel'],
  channelRegion: ['channel', 'region'],
  none: [],
};
let say = () => { };
export function setup(api, log) {
  say = log;
  const off = [
    api.on('groupingChanged', ({ groupBy }) => log(groupBy.length
      ? `Grouping order: ${groupBy.map((id) => titles[id] ?? id).join(' → ')}`
      : 'Not grouped.')),
    api.on('selectionChanged', ({ selectedKeys }) => log(`${selectedKeys.length} rows selected.`)),
  ];
  return () => off.forEach((fn) => fn());
}
function setLevel(value) {
  const box = document.getElementById('level');
  if (box instanceof HTMLSelectElement)
    box.value = value;
}
export const actions = {
  by: (api, value) => api.setGroupBy(orders[value ?? 'region'] ?? []),
  level: (api, value) => {
    const depth = Number(value ?? '1');
    api.expandToDepth(depth);
    say(depth === 0 ? 'Collapsed all.' : `Expanded to level ${depth}.`);
  },
  expandAll: (api) => {
    api.expandAll();
    setLevel('2'); // keep the expand-level select in sync with the current state
  },
  collapseAll: (api) => {
    api.collapseAll();
    setLevel('0');
  },
};