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

컬럼 붙이고 빼기Add and remove columns

컬럼 정의를 통째로 바꿔서 컬럼을 늘리거나 줄여요. 같은 컬럼은 사용자가 바꾼 폭·순서·고정을 그대로 지키고, 새 컬럼은 맨 끝에 붙어요.Replace the whole column list to grow or shrink it. Existing columns keep the width, order and pin the user chose, and new ones are added at the end.

입문Beginner
직접 써 보기Live preview컬럼 붙이고 빼기Add and remove columns

코드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="add">컬럼 붙이기</button>
    <button type="button" id="remove">컬럼 빼기</button>
    <button type="button" id="reset">처음 3개로</button>
  </div>
  <div id="grid" style="height: 200px"></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('add').addEventListener('click', () => actions.add(api));
document.getElementById('remove').addEventListener('click', () => actions.remove(api));
document.getElementById('reset').addEventListener('click', () => actions.reset(api));
example.js
const day = (value) => value instanceof Date
  ? `${value.getFullYear()}-${String(value.getMonth() + 1).padStart(2, '0')}-${String(value.getDate()).padStart(2, '0')}`
  : '';
// 쓸 수 있는 컬럼 전체. 처음에는 앞의 3개만 보여요.
const ALL = [
  { id: 'id', title: '사번', width: 80, align: 'end' },
  { id: 'name', title: '이름', width: 120 },
  { id: 'team', title: '팀', width: 120 },
  { id: 'level', title: '직급', width: 90 },
  { id: 'city', title: '근무지', width: 100 },
  { id: 'salary', title: '연봉(만원)', kind: 'number', width: 120, align: 'end' },
  { id: 'joined', title: '입사일', kind: 'date', width: 120, formatValue: day },
];
/** 컬럼이 이만큼보다 적어지면 더 지울 수 없어요. */
const MIN = 2;
export const options = {
  columns: ALL.slice(0, 3),
  rows: [
    {
      id: 1001,
      name: '김민준',
      team: '개발팀',
      level: '과장',
      city: '서울',
      salary: 6200,
      joined: new Date(2019, 2, 4),
    },
    {
      id: 1002,
      name: '이서연',
      team: '디자인팀',
      level: '대리',
      city: '부산',
      salary: 4800,
      joined: new Date(2021, 6, 12),
    },
    {
      id: 1003,
      name: '박지호',
      team: '영업팀',
      level: '차장',
      city: '대구',
      salary: 7100,
      joined: new Date(2016, 10, 21),
    },
    {
      id: 1004,
      name: '최유나',
      team: '인사팀',
      level: '사원',
      city: '서울',
      salary: 3900,
      joined: new Date(2024, 0, 8),
    },
  ],
  rowKey: 'id',
};
let say = () => { };
// 더 붙이거나 뺄 수 없을 때는 버튼을 흐리게 해서, 눌러도 아무 일 없는 이유를 미리 보여 줘요.
function refreshButtons(api) {
  const count = api.getColumns().length;
  const set = (id, disabled) => {
    const el = document.getElementById(id);
    if (el instanceof HTMLButtonElement)
      el.disabled = disabled;
  };
  set('add', count >= ALL.length);
  set('remove', count <= MIN);
}
// setColumns는 컬럼 정의를 통째로 바꿔요. id가 같은 컬럼은 사용자가 바꾼 폭·순서·고정을 그대로 지키고,
// 새 id는 끝에 붙어요.
export function setup(api, log) {
  say = log;
  refreshButtons(api);
  return () => { };
}
export const actions = {
  add: (api) => {
    const have = new Set(api.getColumns().map((c) => c.id));
    const next = ALL.find((c) => !have.has(c.id));
    if (!next)
      return say({ ko: '붙일 컬럼이 더 없어요', en: 'No more columns to add' });
    api.setColumns([...api.getColumns(), next]);
    say({
      ko: `'${next.title}' 컬럼을 붙였어요 (지금 ${api.getColumns().length}개)`,
      en: `Added the '${next.title}' column (${api.getColumns().length} now)`,
    });
    refreshButtons(api);
  },
  remove: (api) => {
    const current = api.getColumns();
    if (current.length <= MIN)
      return say({
        ko: `컬럼은 ${MIN}개 아래로 줄이지 않아요`,
        en: `Columns will not go below ${MIN}`,
      });
    const last = current[current.length - 1];
    api.setColumns(current.slice(0, -1));
    say({
      ko: `'${last?.title}' 컬럼을 뺐어요 (지금 ${api.getColumns().length}개)`,
      en: `Removed the '${last?.title}' column (${api.getColumns().length} now)`,
    });
    refreshButtons(api);
  },
  reset: (api) => {
    api.setColumns(ALL.slice(0, 3));
    say({ ko: '처음 3개 컬럼으로 되돌렸어요', en: 'Back to the first 3 columns' });
    refreshButtons(api);
  },
};

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="add">Add column</button>
    <button type="button" id="remove">Remove column</button>
    <button type="button" id="reset">Back to 3</button>
  </div>
  <div id="grid" style="height: 200px"></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('add').addEventListener('click', () => actions.add(api));
document.getElementById('remove').addEventListener('click', () => actions.remove(api));
document.getElementById('reset').addEventListener('click', () => actions.reset(api));
example.js
const day = (value) => value instanceof Date
  ? `${value.getFullYear()}-${String(value.getMonth() + 1).padStart(2, '0')}-${String(value.getDate()).padStart(2, '0')}`
  : '';
// Every column that can be used. At first only the first 3 are shown.
const ALL = [
  { id: 'id', title: 'Emp ID', width: 90, align: 'end' },
  { id: 'name', title: 'Name', width: 120 },
  { id: 'team', title: 'Team', width: 120 },
  { id: 'level', title: 'Level', width: 90 },
  { id: 'city', title: 'Office', width: 100 },
  { id: 'salary', title: 'Salary ($)', kind: 'number', width: 120, align: 'end' },
  { id: 'joined', title: 'Joined', kind: 'date', width: 120, formatValue: day },
];
/** Columns cannot be removed below this count. */
const MIN = 2;
export const options = {
  columns: ALL.slice(0, 3),
  rows: [
    {
      id: 1001,
      name: 'Liam Carter',
      team: 'Dev',
      level: 'Manager',
      city: 'Seattle',
      salary: 62000,
      joined: new Date(2019, 2, 4),
    },
    {
      id: 1002,
      name: 'Emma Stone',
      team: 'Design',
      level: 'Associate',
      city: 'Boston',
      salary: 48000,
      joined: new Date(2021, 6, 12),
    },
    {
      id: 1003,
      name: 'Noah Hayes',
      team: 'Sales',
      level: 'Senior Manager',
      city: 'Denver',
      salary: 71000,
      joined: new Date(2016, 10, 21),
    },
    {
      id: 1004,
      name: 'Olivia Reed',
      team: 'HR',
      level: 'Junior',
      city: 'Seattle',
      salary: 39000,
      joined: new Date(2024, 0, 8),
    },
  ],
  rowKey: 'id',
};
let say = () => { };
// When nothing more can be added or removed, the button is dimmed so the reason a press does nothing is visible beforehand.
function refreshButtons(api) {
  const count = api.getColumns().length;
  const set = (id, disabled) => {
    const el = document.getElementById(id);
    if (el instanceof HTMLButtonElement)
      el.disabled = disabled;
  };
  set('add', count >= ALL.length);
  set('remove', count <= MIN);
}
// setColumns replaces the whole column definition. Columns with the same id keep the width, order and pin the user changed,
// and new ids are appended at the end.
export function setup(api, log) {
  say = log;
  refreshButtons(api);
  return () => { };
}
export const actions = {
  add: (api) => {
    const have = new Set(api.getColumns().map((c) => c.id));
    const next = ALL.find((c) => !have.has(c.id));
    if (!next)
      return say('No more columns to add');
    api.setColumns([...api.getColumns(), next]);
    say(`Added the '${next.title}' column (${api.getColumns().length} now)`);
    refreshButtons(api);
  },
  remove: (api) => {
    const current = api.getColumns();
    if (current.length <= MIN)
      return say(`Columns will not go below ${MIN}`);
    const last = current[current.length - 1];
    api.setColumns(current.slice(0, -1));
    say(`Removed the '${last?.title}' column (${api.getColumns().length} now)`);
    refreshButtons(api);
  },
  reset: (api) => {
    api.setColumns(ALL.slice(0, 3));
    say('Back to the first 3 columns');
    refreshButtons(api);
  },
};