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

표의 선택·정렬을 화면 상태와 맞추기Keep the grid's selection and sort in step with screen state

표가 고른 행과 정렬을 알려 주면 화면이 그 값을 자기 상태로 들고 있고, 화면이 상태를 바꾸면 표도 따라 바뀌어요. React, Vue, Angular 탭에는 각 프레임워크의 방식으로 쓴 같은 예제가 들어 있어요.The grid reports the chosen rows and the sort, the screen keeps them as its own state, and when the screen changes its state the grid follows. The React, Vue and Angular tabs hold the same example written the way each framework does it.

활용Intermediate
직접 써 보기Live preview표의 선택·정렬을 화면 상태와 맞추기Keep the grid's selection and sort in step with screen state

실행 화면은 JavaScript 버전이에요. 아래 탭의 React·Vue·Angular 코드는 같은 예제를 각 프레임워크로 직접 쓴 코드예요.The preview runs the JavaScript version. The React, Vue, Angular tabs below hold the same example written for each framework.

코드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">
    <button type="button" id="selectThree">앞의 3명 고르기</button>
    <button type="button" id="sortBySalary">월급 큰 순</button>
    <button type="button" id="reset">처음으로</button>
  </div>
  <div id="grid" style="height: 420px"></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);
document.getElementById('selectThree').addEventListener('click', () => actions.selectThree(api));
document.getElementById('sortBySalary').addEventListener('click', () => actions.sortBySalary(api));
document.getElementById('reset').addEventListener('click', () => actions.reset(api));
example.js
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
export const options = {
  columns: [
    { id: 'name', title: '이름', width: 130 },
    { id: 'dept', title: '부서', width: 120 },
    {
      id: 'salary',
      title: '월급(만원)',
      kind: 'number',
      width: 120,
      align: 'end',
      formatValue: (value) => Number(value).toLocaleString('ko-KR'),
    },
  ],
  rows: [
    { id: 1, name: '김민준', dept: '개발팀', salary: 520 },
    { id: 2, name: '이서연', dept: '디자인팀', salary: 480 },
    { id: 3, name: '박지호', dept: '영업팀', salary: 450 },
    { id: 4, name: '최유나', dept: '개발팀', salary: 610 },
    { id: 5, name: '정도윤', dept: '영업팀', salary: 390 },
    { id: 6, name: '한소희', dept: '디자인팀', salary: 540 },
  ],
  rowKey: 'id',
  selection: { mode: 'multiple', checkbox: true },
};
// 표가 고른 행과 정렬을 알려 주면, 화면(바깥)은 그 값을 자기 상태로 들고 있어요.
// 거꾸로 화면이 상태를 바꾸면 표도 따라 바뀌어요. 아래 코드는 이 JavaScript 버전이에요.
const state = { selected: [], sort: [] };
let line = null;
/** 정렬 상태를 화면에 보여 줄 말로 바꿔요. 예: '월급 ▼'. 모든 탭이 같은 말을 써요. */
export function sortWords(sort, en = false) {
  const names = en
    ? { name: 'Name', dept: 'Department', salary: 'Pay' }
    : { name: '이름', dept: '부서', salary: '월급' };
  return (sort
    .map((s) => `${names[s.columnId] ?? s.columnId} ${s.direction === 'asc' ? '▲' : '▼'}`)
    .join(', ') || (en ? 'none' : '없음'));
}
const show = () => {
  if (!line)
    return;
  line.textContent = L(`고른 행 ${state.selected.length}개 · 정렬 ${sortWords(state.sort)}`, `${state.selected.length} rows selected · sort ${sortWords(state.sort, true)}`);
};
export function setup(api) {
  line = document.createElement('div');
  line.style.cssText = 'font-size: 13px; color: var(--muted); margin: 0 0 8px;';
  document.querySelector('.toolbar')?.insertAdjacentElement('afterend', line);
  state.selected = [];
  state.sort = [];
  show();
  const offs = [
    api.on('selectionChanged', ({ selectedKeys }) => {
      state.selected = selectedKeys;
      show();
    }),
    api.on('sortChanged', ({ sortModel }) => {
      state.sort = sortModel;
      show();
    }),
  ];
  return () => {
    offs.forEach((off) => off());
    line?.remove();
    line = null;
  };
}
export const actions = {
  selectThree: (api) => api.setSelectedKeys([1, 2, 3]),
  sortBySalary: (api) => api.setSortModel([{ columnId: 'salary', direction: 'desc' }]),
  reset: (api) => {
    api.clearSelection();
    api.setSortModel([]);
  },
};

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">
    <button type="button" id="selectThree">Select first three</button>
    <button type="button" id="sortBySalary">Salary high to low</button>
    <button type="button" id="reset">Reset</button>
  </div>
  <div id="grid" style="height: 420px"></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);
document.getElementById('selectThree').addEventListener('click', () => actions.selectThree(api));
document.getElementById('sortBySalary').addEventListener('click', () => actions.sortBySalary(api));
document.getElementById('reset').addEventListener('click', () => actions.reset(api));
example.js
export const options = {
  columns: [
    { id: 'name', title: 'Name', width: 130 },
    { id: 'dept', title: 'Department', width: 120 },
    {
      id: 'salary',
      title: 'Pay ($100)',
      kind: 'number',
      width: 120,
      align: 'end',
      formatValue: (value) => Number(value).toLocaleString('en-US'),
    },
  ],
  rows: [
    { id: 1, name: 'Liam Carter', dept: 'Dev', salary: 520 },
    { id: 2, name: 'Emma Stone', dept: 'Design', salary: 480 },
    { id: 3, name: 'Noah Reed', dept: 'Sales', salary: 450 },
    { id: 4, name: 'Olivia Hayes', dept: 'Dev', salary: 610 },
    { id: 5, name: 'Ethan Brooks', dept: 'Sales', salary: 390 },
    { id: 6, name: 'Sophia Bell', dept: 'Design', salary: 540 },
  ],
  rowKey: 'id',
  selection: { mode: 'multiple', checkbox: true },
};
// When the table reports the selected rows and the sort, the screen (outside) holds those values as its own state.
// Conversely, when the screen changes the state, the table follows. The code below is this JavaScript version.
const state = { selected: [], sort: [] };
let line = null;
/** Turns the sort state into text to show on screen. Example: 'Pay ▼'. Every tab uses the same text. */
export function sortWords(sort, _en = true) {
  const names = { name: 'Name', dept: 'Department', salary: 'Pay' };
  return (sort
    .map((s) => `${names[s.columnId] ?? s.columnId} ${s.direction === 'asc' ? '▲' : '▼'}`)
    .join(', ') || 'none');
}
const show = () => {
  if (!line)
    return;
  line.textContent = `${state.selected.length} rows selected · sort ${sortWords(state.sort, true)}`;
};
export function setup(api) {
  line = document.createElement('div');
  line.style.cssText = 'font-size: 13px; color: var(--muted); margin: 0 0 8px;';
  document.querySelector('.toolbar')?.insertAdjacentElement('afterend', line);
  state.selected = [];
  state.sort = [];
  show();
  const offs = [
    api.on('selectionChanged', ({ selectedKeys }) => {
      state.selected = selectedKeys;
      show();
    }),
    api.on('sortChanged', ({ sortModel }) => {
      state.sort = sortModel;
      show();
    }),
  ];
  return () => {
    offs.forEach((off) => off());
    line?.remove();
    line = null;
  };
}
export const actions = {
  selectThree: (api) => api.setSelectedKeys([1, 2, 3]),
  sortBySalary: (api) => api.setSortModel([{ columnId: 'salary', direction: 'desc' }]),
  reset: (api) => {
    api.clearSelection();
    api.setSortModel([]);
  },
};