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

표에서 고르고 폼으로 고치기Pick in the grid, edit in a form

표에서 줄을 누르면 그 줄 아래에 폼이 열리고 값이 채워져요. 표의 칸은 직접 못 고치게 하고, 폼에서 고친 값을 적용해서 표에 넣어요. 1.6.0부터는 rowEditPanel 옵션으로 같은 일을 더 간단하게 할 수 있어요(예제 "줄을 두 번 눌러 옆 폼에서 고치기" 참고).Click a row and a form opens under it, filled with that row's values. Cells are not editable in the grid; changes are made in the form and applied to the table. From 1.6.0 the rowEditPanel option does the same more simply (see the example "Edit a row in a side form").

입문Beginner
직접 써 보기Live preview표에서 고르고 폼으로 고치기Pick in the grid, edit in a form

코드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 id="grid" style="height: 470px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
example.js
const names = ['김서연', '이준호', '박민지', '최도윤', '정하은', '강지후', '윤서아', '임태민'];
const cities = ['서울', '부산', '대구', '인천', '광주', '대전'];
const colors = ['블랙', '화이트', '실버', '네이비', '핑크'];
const products = ['무선 이어폰', '노트북 14형', '스마트워치', '태블릿 11형', '보조배터리'];
const rows = names.map((name, i) => ({
  id: `C${String(i + 1).padStart(3, '0')}`,
  name,
  city: cities[(i * 5) % cities.length],
  color: colors[(i * 3) % colors.length],
  product: products[(i * 2 + 1) % products.length],
  price: 59000 + ((i * 7) % 9) * 30000,
  date: `2026-0${1 + (i % 9)}-${String(5 + i * 2).padStart(2, '0')}`,
}));
let gridApi = null;
// 폼 패널 높이는 폼이 실제로 차지하는 높이를 재서 정해요(폼은 폭에 따라 줄바꿈되기 때문이에요).
let panelHeight = 160;
let showCell = () => { };
let say = () => { };
// 줄을 고르면 그 줄 아래에 폼이 열려요. 폼은 상세 패널(detail)로 만든 거라 그리드 안에서 같이 움직여요.
// 그리드 칸은 직접 고칠 수 없고(editable을 주지 않았어요), 폼에서 고친 값을 "적용"으로 그 줄에 넣어요.
const panel = () => {
  let current;
  let info;
  let message;
  let observer = null;
  const inputs = {
    name: document.createElement('input'),
    product: document.createElement('input'),
    price: document.createElement('input'),
    color: document.createElement('select'),
  };
  const fill = (row) => {
    current = row;
    inputs.name.value = row.name;
    inputs.product.value = row.product;
    inputs.price.value = String(row.price);
    inputs.color.value = row.color;
    message.textContent = '';
    info.textContent = `고객 번호 ${row.id} · ${gridApi ? gridApi.getVisibleIndexOfKey(row.id) + 1 : '?'}번째 줄`;
  };
  // 색은 모두 그리드의 테마 변수(--mxg-*)에서 가져와서 다크 모드에서도 그대로 어울려요.
  const field = (label, input) => {
    const wrap = document.createElement('label');
    wrap.style.cssText =
      'display: flex; flex-direction: column; gap: 2px; font-size: 12px; color: var(--mxg-fg-muted);';
    input.style.cssText =
      'font: inherit; font-size: 13px; padding: 4px 6px; background: var(--mxg-bg); color: var(--mxg-fg); border: 1px solid var(--mxg-border); border-radius: var(--mxg-radius); min-width: 0;';
    wrap.append(label, input);
    return wrap;
  };
  const button = (text, onClick) => {
    const b = document.createElement('button');
    b.type = 'button';
    b.textContent = text;
    b.style.cssText =
      'font: inherit; font-size: 13px; padding: 4px 12px; background: var(--mxg-bg); color: var(--mxg-fg); border: 1px solid var(--mxg-border); border-radius: var(--mxg-radius); cursor: pointer;';
    b.addEventListener('click', onClick);
    return b;
  };
  const fail = (text) => {
    message.style.color = 'var(--mxg-danger)';
    message.textContent = text;
  };
  const apply = () => {
    const price = Number(inputs.price.value.replaceAll(',', '').trim());
    if (!inputs.name.value.trim())
      return fail('이름을 입력해 주세요.');
    if (inputs.price.value.trim() === '' || !Number.isFinite(price) || price < 0) {
      return fail('가격은 0 이상의 숫자로 써 주세요.');
    }
    gridApi?.updateRows([
      {
        ...current,
        name: inputs.name.value.trim(),
        product: inputs.product.value.trim(),
        color: inputs.color.value,
        price,
      },
    ]);
    message.style.color = 'var(--mxg-fg-muted)';
    message.textContent = '적용했어요.';
    say({
      ko: `${current.id} 줄에 적용했어요: ${inputs.name.value.trim()} · ${inputs.product.value.trim()} · ${price.toLocaleString('ko-KR')}원 · ${inputs.color.value}`,
      en: `Applied to row ${current.id}: ${inputs.name.value.trim()} · ${inputs.product.value.trim()} · ${price.toLocaleString('en-US')} KRW · ${inputs.color.value}`,
    });
  };
  return {
    mount(element, { row }) {
      // style 전체를 덮어쓰면 그리드가 정해 준 너비·위치가 사라져요. 필요한 속성만 하나씩 넣어요.
      Object.assign(element.style, {
        padding: '8px 16px',
        display: 'flex',
        flexDirection: 'column',
        gap: '8px',
      });
      info = document.createElement('div');
      info.style.cssText = 'font-weight: 600;';
      const lastCell = document.createElement('div');
      lastCell.style.cssText = 'font-size: 12px; color: var(--mxg-fg-muted);';
      lastCell.textContent = '표의 칸을 누르면 어느 컬럼을 눌렀는지 여기에 나와요.';
      showCell = (text) => (lastCell.textContent = text);
      for (const color of colors)
        inputs.color.append(new Option(color, color));
      message = document.createElement('span');
      message.style.cssText = 'font-size: 12px;';
      const form = document.createElement('div');
      form.style.cssText = 'display: flex; flex-wrap: wrap; gap: 8px; align-items: flex-end;';
      form.append(field('이름', inputs.name), field('상품', inputs.product), field('가격', inputs.price), field('색상', inputs.color), button('적용', apply), button('되돌리기', () => fill(current)), message);
      // 패널은 표 전체 폭만큼 넓어서 좁은 화면에서는 옆으로 밀려요. 내용을 화면에 보이는 폭에 맞춰 왼쪽에 붙여 줘요.
      const box = document.createElement('div');
      Object.assign(box.style, {
        position: 'sticky',
        left: '0',
        display: 'flex',
        flexDirection: 'column',
        gap: '8px',
      });
      box.append(info, lastCell, form);
      element.append(box);
      const view = element.closest('.mxg');
      const fit = () => {
        if (view)
          box.style.width = `${Math.max(240, view.clientWidth - 32)}px`;
      };
      fit();
      // 폼 높이를 재서 패널 높이로 알려 줘요. 폭이 바뀌어 줄바꿈이 달라지면 다시 재요.
      const measure = () => {
        const wanted = Math.ceil(box.offsetHeight) + 18;
        if (wanted !== panelHeight) {
          panelHeight = wanted;
          gridApi?.refresh();
        }
      };
      observer = new ResizeObserver(() => {
        fit();
        measure();
      });
      if (view)
        observer.observe(view);
      observer.observe(box);
      measure();
      fill(row);
    },
    update({ row }) {
      fill(row);
    },
    destroy() {
      observer?.disconnect();
      showCell = () => { };
    },
  };
};
export const options = {
  columns: [
    { id: 'id', title: '고객 번호', width: 100 },
    { id: 'name', title: '이름', width: 90 },
    { id: 'city', title: '지역', width: 80 },
    { id: 'color', title: '색상', width: 80 },
    { id: 'product', title: '상품', width: 140 },
    {
      id: 'price',
      title: '가격',
      kind: 'number',
      width: 110,
      align: 'end',
      formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}원`,
    },
    { id: 'date', title: '주문일', width: 110 },
  ],
  rows,
  rowKey: 'id',
  selection: 'single',
  // 폼이 줄바꿈되는 만큼 패널도 높아져요: 넓으면 한 줄, 좁으면 입력칸이 줄마다 하나씩 쌓여요.
  detail: { renderer: panel, height: () => panelHeight },
};
// 줄을 고르면 폼이 그 줄로 열리고 다른 줄의 폼은 닫혀요. 폼은 열릴 때마다 그 줄의 값으로 새로 채워져요.
export function setup(api, log) {
  gridApi = api;
  say = log;
  log({
    ko: '줄을 하나 눌러 보세요. 그 줄 아래에 폼이 열려요.',
    en: 'Click a row. A form opens under it.',
  });
  const offs = [
    api.on('selectionChanged', ({ selectedKeys }) => {
      for (const row of api.getRows())
        if (api.isDetailExpanded(row.id))
          api.collapseDetail(row.id);
      const key = selectedKeys[0];
      if (key !== undefined)
        api.expandDetail(key);
    }),
    api.on('cellClicked', ({ rowKey, columnId }) => {
      const title = api.getColumns().find((c) => c.id === columnId)?.title ?? columnId;
      const text = `누른 칸: ${api.getVisibleIndexOfKey(rowKey) + 1}번째 줄, "${title}" 컬럼 (id: ${columnId})`;
      showCell(text);
      log(text);
    }),
  ];
  return () => {
    offs.forEach((off) => off());
  };
}

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 id="grid" style="height: 470px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
example.js
const names = [
  'Liam Carter',
  'Emma Stone',
  'Noah Brooks',
  'Olivia Reed',
  'Ethan Hayes',
  'Ava Morgan',
  'Mason Clark',
  'Sophia Bell',
];
const cities = ['Seoul', 'Busan', 'Daegu', 'Incheon', 'Gwangju', 'Daejeon'];
const colors = ['Black', 'White', 'Silver', 'Navy', 'Pink'];
const products = ['Wireless Earbuds', 'Laptop 14"', 'Smartwatch', 'Tablet 11"', 'Power Bank'];
const rows = names.map((name, i) => ({
  id: `C${String(i + 1).padStart(3, '0')}`,
  name,
  city: cities[(i * 5) % cities.length],
  color: colors[(i * 3) % colors.length],
  product: products[(i * 2 + 1) % products.length],
  price: 59 + ((i * 7) % 9) * 30,
  date: `2026-0${1 + (i % 9)}-${String(5 + i * 2).padStart(2, '0')}`,
}));
let gridApi = null;
// The form panel height is set by measuring the height the form actually takes (the form wraps depending on width).
let panelHeight = 160;
let showCell = () => { };
let say = () => { };
// Picking a row opens a form under it. The form is built as a detail panel, so it moves together with the grid.
// Grid cells cannot be edited directly (editable is not set); values changed in the form are put into that row with "Apply".
const panel = () => {
  let current;
  let info;
  let message;
  let observer = null;
  const inputs = {
    name: document.createElement('input'),
    product: document.createElement('input'),
    price: document.createElement('input'),
    color: document.createElement('select'),
  };
  const fill = (row) => {
    current = row;
    inputs.name.value = row.name;
    inputs.product.value = row.product;
    inputs.price.value = String(row.price);
    inputs.color.value = row.color;
    message.textContent = '';
    info.textContent = `Customer ${row.id} · row ${gridApi ? gridApi.getVisibleIndexOfKey(row.id) + 1 : '?'}`;
  };
  // All colors come from the grid's theme variables (--mxg-*), so they also fit in dark mode.
  const field = (label, input) => {
    const wrap = document.createElement('label');
    wrap.style.cssText =
      'display: flex; flex-direction: column; gap: 2px; font-size: 12px; color: var(--mxg-fg-muted);';
    input.style.cssText =
      'font: inherit; font-size: 13px; padding: 4px 6px; background: var(--mxg-bg); color: var(--mxg-fg); border: 1px solid var(--mxg-border); border-radius: var(--mxg-radius); min-width: 0;';
    wrap.append(label, input);
    return wrap;
  };
  const button = (text, onClick) => {
    const b = document.createElement('button');
    b.type = 'button';
    b.textContent = text;
    b.style.cssText =
      'font: inherit; font-size: 13px; padding: 4px 12px; background: var(--mxg-bg); color: var(--mxg-fg); border: 1px solid var(--mxg-border); border-radius: var(--mxg-radius); cursor: pointer;';
    b.addEventListener('click', onClick);
    return b;
  };
  const fail = (text) => {
    message.style.color = 'var(--mxg-danger)';
    message.textContent = text;
  };
  const apply = () => {
    const price = Number(inputs.price.value.replaceAll(',', '').trim());
    if (!inputs.name.value.trim())
      return fail('Please enter a name.');
    if (inputs.price.value.trim() === '' || !Number.isFinite(price) || price < 0) {
      return fail('Enter the price as a number of 0 or more.');
    }
    gridApi?.updateRows([
      {
        ...current,
        name: inputs.name.value.trim(),
        product: inputs.product.value.trim(),
        color: inputs.color.value,
        price,
      },
    ]);
    message.style.color = 'var(--mxg-fg-muted)';
    message.textContent = 'Applied.';
    say(`Applied to row ${current.id}: ${inputs.name.value.trim()} · ${inputs.product.value.trim()} · $${price.toLocaleString('en-US')} · ${inputs.color.value}`);
  };
  return {
    mount(element, { row }) {
      // Overwriting the whole style would erase the width and position the grid set. Add only the properties we need, one by one.
      Object.assign(element.style, {
        padding: '8px 16px',
        display: 'flex',
        flexDirection: 'column',
        gap: '8px',
      });
      info = document.createElement('div');
      info.style.cssText = 'font-weight: 600;';
      const lastCell = document.createElement('div');
      lastCell.style.cssText = 'font-size: 12px; color: var(--mxg-fg-muted);';
      lastCell.textContent = 'Click a cell in the table and the column you clicked appears here.';
      showCell = (text) => (lastCell.textContent = text);
      for (const color of colors)
        inputs.color.append(new Option(color, color));
      message = document.createElement('span');
      message.style.cssText = 'font-size: 12px;';
      const form = document.createElement('div');
      form.style.cssText = 'display: flex; flex-wrap: wrap; gap: 8px; align-items: flex-end;';
      form.append(field('Name', inputs.name), field('Product', inputs.product), field('Price', inputs.price), field('Color', inputs.color), button('Apply', apply), button('Reset', () => fill(current)), message);
      // The panel is as wide as the whole table, so on a narrow screen it is pushed sideways. Fit the content to the visible width and pin it to the left.
      const box = document.createElement('div');
      Object.assign(box.style, {
        position: 'sticky',
        left: '0',
        display: 'flex',
        flexDirection: 'column',
        gap: '8px',
      });
      box.append(info, lastCell, form);
      element.append(box);
      const view = element.closest('.mxg');
      const fit = () => {
        if (view)
          box.style.width = `${Math.max(240, view.clientWidth - 32)}px`;
      };
      fit();
      // Measure the form height and report it as the panel height. Measure again when the width changes and the wrapping differs.
      const measure = () => {
        const wanted = Math.ceil(box.offsetHeight) + 18;
        if (wanted !== panelHeight) {
          panelHeight = wanted;
          gridApi?.refresh();
        }
      };
      observer = new ResizeObserver(() => {
        fit();
        measure();
      });
      if (view)
        observer.observe(view);
      observer.observe(box);
      measure();
      fill(row);
    },
    update({ row }) {
      fill(row);
    },
    destroy() {
      observer?.disconnect();
      showCell = () => { };
    },
  };
};
export const options = {
  columns: [
    { id: 'id', title: 'Customer ID', width: 110 },
    { id: 'name', title: 'Name', width: 120 },
    { id: 'city', title: 'City', width: 80 },
    { id: 'color', title: 'Color', width: 80 },
    { id: 'product', title: 'Product', width: 150 },
    {
      id: 'price',
      title: 'Price',
      kind: 'number',
      width: 110,
      align: 'end',
      formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
    },
    { id: 'date', title: 'Order date', width: 110 },
  ],
  rows,
  rowKey: 'id',
  selection: 'single',
  // The panel grows as tall as the form wraps: one line when wide, one input per line when narrow.
  detail: { renderer: panel, height: () => panelHeight },
};
// Picking a row opens the form for that row and closes the forms of other rows. Each time the form opens it is refilled with that row's values.
export function setup(api, log) {
  gridApi = api;
  say = log;
  log('Click a row. A form opens under it.');
  const offs = [
    api.on('selectionChanged', ({ selectedKeys }) => {
      for (const row of api.getRows())
        if (api.isDetailExpanded(row.id))
          api.collapseDetail(row.id);
      const key = selectedKeys[0];
      if (key !== undefined)
        api.expandDetail(key);
    }),
    api.on('cellClicked', ({ rowKey, columnId }) => {
      const title = api.getColumns().find((c) => c.id === columnId)?.title ?? columnId;
      const text = `Clicked cell: row ${api.getVisibleIndexOfKey(rowKey) + 1}, "${title}" column (id: ${columnId})`;
      showCell(text);
      log(text);
    }),
  ];
  return () => {
    offs.forEach((off) => off());
  };
}