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

칸을 직접 고치기Edit cells in place

글자·숫자 칸은 더블클릭하거나 눌러 둔 채로 바로 입력하면 고칠 수 있고, 목록과 체크박스 칸은 한 번 누르면 돼요. 글자·숫자·목록·체크박스마다 알맞은 편집기가 열리고, 규칙에 어긋나면 확정되지 않고 이유가 나와요.Double-click a cell, or select it and just type. Text, numbers, lists and checkboxes each open a fitting editor, and a value that breaks a rule is refused with a reason.

입문Beginner
직접 써 보기Live preview칸을 직접 고치기Edit cells in place

코드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="scope">
      <option value="all" selected>모든 컬럼</option>
      <option value="name">이름만</option>
      <option value="none">없음 (읽기 전용)</option>
    </select>
  </div>
  <div id="grid" style="height: 360px"></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('scope').addEventListener('change', (event) => actions.scope(api, event.target.value));
example.js
const names = ['김서연', '이준호', '박민지', '최도윤', '정하은', '강지후', '윤서아', '임태민'];
const departments = ['개발', '디자인', '기획', '영업'];
const rows = names.map((name, i) => ({
  id: i + 1,
  name,
  department: departments[i % departments.length],
  salary: 3800 + ((i * 7) % 9) * 250,
  active: i !== 5,
}));
let scope = 'all';
// 컬럼에 editable: true를 주면 그 컬럼의 칸을 고칠 수 있어요. 어떤 편집기가 열릴지는 컬럼 종류(kind)가 정해요:
// 글자는 입력칸, 숫자는 숫자 입력칸, select는 목록, boolean은 체크박스예요.
// validation은 확정 전에 값을 검사해요. 규칙에 어긋나면 확정되지 않고 이유가 나와요.
const columns = () => {
  const can = (id) => scope === 'all' || (scope === 'name' && id === 'name');
  return [
    { id: 'id', title: '번호', width: 70, align: 'end' },
    {
      id: 'name',
      title: '이름',
      width: 120,
      editable: can('name'),
      validation: { required: true, maxLength: 6 },
    },
    {
      id: 'department',
      title: '부서',
      kind: 'select',
      width: 110,
      editable: can('other'),
      editorOptions: departments.map((value) => ({ value })),
    },
    {
      id: 'salary',
      title: '월급(만원)',
      kind: 'number',
      width: 120,
      align: 'end',
      editable: can('other'),
      validation: { min: 0 },
    },
    {
      id: 'active',
      title: '재직',
      kind: 'boolean',
      width: 80,
      align: 'center',
      editable: can('other'),
      cellRenderer: 'checkbox',
    },
  ];
};
export const options = {
  columns: columns(),
  rows,
  rowKey: 'id',
};
const titleOf = (api, id) => api.getColumns().find((c) => c.id === id)?.title ?? id;
export function setup(api, log) {
  // 글자·숫자 칸은 더블클릭이고, 목록(부서)과 체크박스(재직) 칸은 한 번 누르면 반응해요(singleClickEdit 기본값).
  log({
    ko: '이름·월급 칸은 더블클릭하거나 눌러 두고 바로 입력해 보세요. 부서(목록)와 재직(체크박스)은 한 번 누르면 돼요.',
    en: 'Double-click the name and pay cells, or select one and just type. The department (list) and active (checkbox) cells need one click.',
  });
  const offs = [
    api.on('editCommitted', (e) => log({
      ko: `${e.rowKey}번 줄의 ${titleOf(api, e.columnId)}: ${String(e.oldValue)} → ${String(e.newValue)}`,
      en: `Row ${e.rowKey} ${titleOf(api, e.columnId)}: ${String(e.oldValue)} → ${String(e.newValue)}`,
    })),
    api.on('editCancelled', () => log({ ko: '편집을 취소했어요.', en: 'Edit cancelled.' })),
    api.on('validationFailed', (e) => log({
      ko: `확정하지 못했어요 (${titleOf(api, e.columnId)}): ${e.message}`,
      en: `Could not confirm (${titleOf(api, e.columnId)}): ${e.message}`,
    })),
  ];
  return () => offs.forEach((off) => off());
}
export const actions = {
  scope: (api, value) => {
    scope = (value ?? 'all');
    api.setColumns(columns());
  },
};

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="Editable cells" id="scope">
      <option value="all" selected>All columns</option>
      <option value="name">Name only</option>
      <option value="none">None (read-only)</option>
    </select>
  </div>
  <div id="grid" style="height: 360px"></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('scope').addEventListener('change', (event) => actions.scope(api, event.target.value));
example.js
const names = [
  'Liam Carter',
  'Emma Stone',
  'Noah Kim',
  'Olivia Park',
  'Ava Hughes',
  'Mason Lee',
  'Zoe Adams',
  'Ethan Cole',
];
const departments = ['Dev', 'Design', 'Planning', 'Sales'];
const rows = names.map((name, i) => ({
  id: i + 1,
  name,
  department: departments[i % departments.length],
  salary: 38000 + ((i * 7) % 9) * 2500,
  active: i !== 5,
}));
let scope = 'all';
// editable: true on a column makes its cells editable. The column kind decides which editor opens:
// text opens an input, number opens a number input, select opens a list, and boolean opens a checkbox.
// validation checks the value before it is confirmed. If a rule is broken, the edit is not confirmed and the reason is shown.
const columns = () => {
  const can = (id) => scope === 'all' || (scope === 'name' && id === 'name');
  return [
    { id: 'id', title: 'No.', width: 70, align: 'end' },
    {
      id: 'name',
      title: 'Name',
      width: 120,
      editable: can('name'),
      validation: { required: true, maxLength: 12 },
    },
    {
      id: 'department',
      title: 'Department',
      kind: 'select',
      width: 130,
      editable: can('other'),
      editorOptions: departments.map((value) => ({ value })),
    },
    {
      id: 'salary',
      title: 'Salary ($)',
      kind: 'number',
      width: 120,
      align: 'end',
      editable: can('other'),
      validation: { min: 0 },
    },
    {
      id: 'active',
      title: 'Active',
      kind: 'boolean',
      width: 80,
      align: 'center',
      editable: can('other'),
      cellRenderer: 'checkbox',
    },
  ];
};
export const options = {
  columns: columns(),
  rows,
  rowKey: 'id',
};
const titleOf = (api, id) => api.getColumns().find((c) => c.id === id)?.title ?? id;
export function setup(api, log) {
  // Text and number cells need a double-click; list (department) and checkbox (active) cells react to a single click (the singleClickEdit default).
  log('Double-click the name and pay cells, or select one and just type. The department (list) and active (checkbox) cells need one click.');
  const offs = [
    api.on('editCommitted', (e) => log(`Row ${e.rowKey} ${titleOf(api, e.columnId)}: ${String(e.oldValue)} -> ${String(e.newValue)}`)),
    api.on('editCancelled', () => log('Edit cancelled.')),
    api.on('validationFailed', (e) => log(`Could not confirm (${titleOf(api, e.columnId)}): ${e.message}`)),
  ];
  return () => offs.forEach((off) => off());
}
export const actions = {
  scope: (api, value) => {
    scope = (value ?? 'all');
    api.setColumns(columns());
  },
};