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

헤더를 끌어 컬럼 순서 바꾸고, 잠그기Drag headers to reorder columns, and lock them

헤더를 끌면 컬럼 순서가 바뀌어요. '번호'처럼 움직이면 안 되는 컬럼은 movable: false로 잠그고, 폭 조절을 막거나 표 전체를 한 번에 잠글 수도 있어요. 코드로 옮기는 것은 잠금과 상관없이 돼요.Drag a header to reorder columns. Lock a column such as ID with movable: false, or lock all moving and resizing at once. Moving by code is never blocked.

입문Beginner
직접 써 보기Live preview헤더를 끌어 컬럼 순서 바꾸고, 잠그기Drag headers to reorder columns, and lock them

코드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="lock">
      <option value="free" selected>풀어 두기 (기본)</option>
      <option value="all">전체 잠금</option>
    </select>
    <button type="button" id="amountFirst">금액을 맨 앞으로 (코드)</button>
    <button type="button" id="groupLast">업무 묶음을 맨 뒤로 (코드)</button>
    <button type="button" id="groupFirst">업무 묶음을 맨 앞으로 (코드)</button>
  </div>
  <div id="grid" style="height: 400px"></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('lock').addEventListener('change', (event) => actions.lock(api, event.target.value));
document.getElementById('amountFirst').addEventListener('click', () => actions.amountFirst(api));
document.getElementById('groupLast').addEventListener('click', () => actions.groupLast(api));
document.getElementById('groupFirst').addEventListener('click', () => actions.groupFirst(api));
example.js
const names = ['김민준', '이서연', '박지호', '최유나', '정도윤'];
const teams = ['개발팀', '디자인팀', '영업팀', '인사팀'];
// 컬럼 순서는 헤더를 끌어서 바꿔요. movable: false인 컬럼은 끌 수 없고,
// columnsMovable·columnsResizable로 그리드 전체를 한 번에 잠글 수도 있어요. 코드(moveColumn)는 잠겨 있어도 돼요.
export const options = {
  columns: [
    { id: 'id', title: '번호 (잠금)', width: 100, movable: false, resizable: false, align: 'end' },
    { id: 'name', title: '이름', width: 130, minWidth: 90, maxWidth: 240 },
    { id: 'team', title: '팀', width: 130 },
    { id: 'status', title: '상태', width: 110 },
    { id: 'amount', title: '금액(원)', kind: 'number', width: 130, align: 'end' },
  ],
  // 묶음(그룹) 제목을 끌면 묶인 컬럼이 한 덩어리로 같이 움직여요.
  headerGroups: [{ id: 'work', title: '업무', children: ['team', 'status'] }],
  rows: Array.from({ length: 6 }, (_, i) => ({
    id: i + 1,
    name: names[i % 5],
    team: teams[(i * 3) % 4],
    status: i % 3 === 0 ? '근무' : i % 3 === 1 ? '휴직' : '출장',
    amount: 190000 + i * 73000,
  })),
  rowKey: 'id',
};
let say = () => { };
export function setup(api, log) {
  say = log;
  // 묶음을 옮기면 컬럼마다 이동 이벤트가 연달아 오기 때문에, 잠깐 모았다가 새 순서를 한 줄로 알려 줘요.
  let timer;
  let by = 'api';
  const titleOf = (id) => api.getColumns().find((c) => c.id === id)?.title ?? id;
  const offs = [
    api.on('columnMoved', (e) => {
      by = e.source;
      clearTimeout(timer);
      timer = setTimeout(() => log({
        ko: `새 순서(${by === 'api' ? '코드' : '직접'}): ${api.getColumnOrder().map(titleOf).join(' · ')}`,
        en: `New order (${by === 'api' ? 'code' : 'direct'}): ${api.getColumnOrder().map(titleOf).join(' · ')}`,
      }), 80);
    }),
    api.on('columnResized', (e) => log({
      ko: `${titleOf(e.columnId)} 폭 ${e.previousWidth} → ${e.width}px`,
      en: `${titleOf(e.columnId)} width ${e.previousWidth} → ${e.width}px`,
    })),
  ];
  return () => {
    clearTimeout(timer);
    offs.forEach((off) => off());
  };
}
function moveWork(api, where) {
  const order = api.getColumnOrder();
  const at = order.indexOf('team');
  const already = where === 'first' ? at === 0 : at === order.length - 2;
  if (already) {
    say({
      ko: `업무 묶음이 이미 맨 ${where === 'first' ? '앞' : '뒤'}에 있어요`,
      en: `The work group is already at the ${where === 'first' ? 'start' : 'end'}`,
    });
    return;
  }
  api.moveColumnGroup('work', where === 'first' ? 0 : order.length - 2);
}
export const actions = {
  // 묶음 전체를 한 덩어리로 옮겨요. 이미 그 자리에 있으면 바뀌는 게 없어서 알려 줘요.
  groupLast: (api) => moveWork(api, 'last'),
  groupFirst: (api) => moveWork(api, 'first'),
  amountFirst: (api) => api.moveColumn('amount', 0),
  lock: (api, value) => api.setOptions(value === 'all'
    ? { columnsMovable: false, columnsResizable: false }
    : { columnsMovable: true, columnsResizable: true }),
};

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="Lock" id="lock">
      <option value="free" selected>Free (default)</option>
      <option value="all">Lock everything</option>
    </select>
    <button type="button" id="amountFirst">Move amount first (code)</button>
    <button type="button" id="groupLast">Move Work group last (code)</button>
    <button type="button" id="groupFirst">Move Work group first (code)</button>
  </div>
  <div id="grid" style="height: 400px"></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('lock').addEventListener('change', (event) => actions.lock(api, event.target.value));
document.getElementById('amountFirst').addEventListener('click', () => actions.amountFirst(api));
document.getElementById('groupLast').addEventListener('click', () => actions.groupLast(api));
document.getElementById('groupFirst').addEventListener('click', () => actions.groupFirst(api));
example.js
const names = ['Liam Carter', 'Emma Stone', 'Noah Hayes', 'Olivia Reed', 'Ethan Cole'];
const teams = ['Dev', 'Design', 'Sales', 'HR'];
// The column order changes by dragging a header. A column with movable: false cannot be dragged,
// and columnsMovable and columnsResizable can lock the whole grid at once. Code (moveColumn) works even when locked.
export const options = {
  columns: [
    { id: 'id', title: 'ID (locked)', width: 100, movable: false, resizable: false, align: 'end' },
    { id: 'name', title: 'Name', width: 130, minWidth: 90, maxWidth: 240 },
    { id: 'team', title: 'Team', width: 130 },
    { id: 'status', title: 'Status', width: 110 },
    { id: 'amount', title: 'Amount ($)', kind: 'number', width: 130, align: 'end' },
  ],
  // Dragging a group title moves the grouped columns together as one block.
  headerGroups: [{ id: 'work', title: 'Work', children: ['team', 'status'] }],
  rows: Array.from({ length: 6 }, (_, i) => ({
    id: i + 1,
    name: names[i % 5],
    team: teams[(i * 3) % 4],
    status: i % 3 === 0 ? 'Working' : i % 3 === 1 ? 'On leave' : 'Traveling',
    amount: 190 + i * 73,
  })),
  rowKey: 'id',
};
let say = () => { };
export function setup(api, log) {
  say = log;
  // Moving a group sends move events one column after another, so collect them briefly and report the new order in one line.
  let timer;
  let by = 'api';
  const titleOf = (id) => api.getColumns().find((c) => c.id === id)?.title ?? id;
  const offs = [
    api.on('columnMoved', (e) => {
      by = e.source;
      clearTimeout(timer);
      timer = setTimeout(() => log(`New order (${by === 'api' ? 'code' : 'direct'}): ${api.getColumnOrder().map(titleOf).join(' · ')}`), 80);
    }),
    api.on('columnResized', (e) => log(`${titleOf(e.columnId)} width ${e.previousWidth} → ${e.width}px`)),
  ];
  return () => {
    clearTimeout(timer);
    offs.forEach((off) => off());
  };
}
function moveWork(api, where) {
  const order = api.getColumnOrder();
  const at = order.indexOf('team');
  const already = where === 'first' ? at === 0 : at === order.length - 2;
  if (already) {
    say(`The work group is already at the ${where === 'first' ? 'start' : 'end'}`);
    return;
  }
  api.moveColumnGroup('work', where === 'first' ? 0 : order.length - 2);
}
export const actions = {
  // Move the whole group as one block. If it is already there nothing changes, so say so.
  groupLast: (api) => moveWork(api, 'last'),
  groupFirst: (api) => moveWork(api, 'first'),
  amountFirst: (api) => api.moveColumn('amount', 0),
  lock: (api, value) => api.setOptions(value === 'all'
    ? { columnsMovable: false, columnsResizable: false }
    : { columnsMovable: true, columnsResizable: true }),
};