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

내가 맞춘 표 모양 기억해 두기Remember the table layout you set

컬럼 순서·너비·숨김·고정과 정렬, 보고 있던 위치를 저장했다가 다시 열 때 그대로 되돌려요. 이 예제는 브라우저 안에 저장하지만 서버 DB에 저장해도 같은 방식이에요.Save column order, width, visibility and pinning plus sorting and scroll position, and restore them next time. This demo uses localStorage, but a server database works the same way.

활용Intermediate
직접 써 보기Live preview내가 맞춘 표 모양 기억해 두기Remember the table layout you set

코드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="hideCity">지역 숨기기</button>
    <button type="button" id="pinName">이름 왼쪽 고정</button>
    <button type="button" id="sortPrice">가격 높은 순</button>
    <button type="button" id="save">상태 저장</button>
    <button type="button" id="load">저장한 상태로</button>
    <button type="button" id="clear">저장 지우고 처음으로</button>
  </div>
  <div id="grid" style="height: 340px"></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('hideCity').addEventListener('click', () => actions.hideCity(api));
document.getElementById('pinName').addEventListener('click', () => actions.pinName(api));
document.getElementById('sortPrice').addEventListener('click', () => actions.sortPrice(api));
document.getElementById('save').addEventListener('click', () => actions.save(api));
document.getElementById('load').addEventListener('click', () => actions.load(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
example.js
const names = ['김서연', '이준호', '박민지', '최도윤', '정하은', '강지후', '윤서아', '임태민'];
const cities = ['서울', '부산', '대구', '인천', '광주', '대전'];
const products = ['무선 이어폰', '노트북 14형', '스마트워치', '태블릿 11형', '보조배터리'];
const colors = ['블랙', '화이트', '실버', '네이비', '핑크'];
const rows = Array.from({ length: 60 }, (_, i) => ({
  id: i + 1,
  name: names[(i * 3) % names.length],
  city: cities[(i * 5) % cities.length],
  product: products[(i * 2 + (i >> 2)) % products.length],
  color: colors[(i * 7) % colors.length],
  quantity: 1 + ((i * 7) % 9),
  price: 29000 + ((i * 7919) % 40) * 10000,
}));
export const options = {
  columns: [
    { id: 'name', title: '이름', width: 100 },
    { id: 'city', title: '지역', width: 90 },
    { id: 'product', title: '상품', width: 140 },
    { id: 'color', title: '색상', width: 90 },
    { id: 'quantity', title: '수량', kind: 'number', width: 80, align: 'end' },
    {
      id: 'price',
      title: '가격',
      kind: 'number',
      width: 110,
      align: 'end',
      formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}원`,
    },
  ],
  rows,
  rowKey: 'id',
  rowHeight: 32,
};
const KEY = 'maxgrid-example-grid-state';
let say = () => { };
let initial = [];
let memory = null; // 브라우저 저장소를 못 쓰는 환경(미리보기 화면 등)에서는 메모리에 둬요.
function read() {
  try {
    return localStorage.getItem(KEY) ?? memory;
  }
  catch {
    return memory;
  }
}
function write(text) {
  memory = text;
  try {
    if (text === null)
      localStorage.removeItem(KEY);
    else
      localStorage.setItem(KEY, text);
  }
  catch {
    say({
      ko: '이 화면에서는 브라우저 저장소를 못 써서, 페이지를 닫기 전까지만 기억해요.',
      en: 'Browser storage is unavailable here, so the state is remembered only until you close the page.',
    });
  }
}
function restore(api) {
  const text = read();
  if (!text)
    return false;
  try {
    const state = JSON.parse(text);
    api.setColumnState(state.columns);
    api.setSortModel(state.sort);
    // 컬럼과 정렬을 먼저 적용한 뒤, 화면이 다시 그려진 다음에 스크롤 위치를 되돌려요.
    requestAnimationFrame(() => requestAnimationFrame(() => api.setScroll(state.scroll ?? { top: 0, left: 0 })));
    return true;
  }
  catch (error) {
    // 깨진 값 때문에 화면이 멈추면 안 돼요. 알리고 기본 상태로 둬요.
    say({
      ko: `저장된 상태가 올바르지 않아 무시했어요: ${String(error)}`,
      en: `Ignored the saved state because it is not valid: ${String(error)}`,
    });
    return false;
  }
}
export function setup(api, log) {
  say = log;
  initial = api.getColumnState();
  log({
    ko: restore(api)
      ? '저장된 상태를 불러왔어요.'
      : '저장된 상태가 없어요. 컬럼을 끌어 옮기거나 너비를 바꾼 뒤 "상태 저장"을 눌러 보세요.',
    en: restore(api)
      ? 'Saved state restored.'
      : 'No saved state. Drag a column or change a width, then press "Save state".',
  });
}
export const actions = {
  save: (api) => {
    const state = {
      columns: api.getColumnState(),
      sort: api.getSortModel(),
      scroll: api.getScroll(),
    };
    write(JSON.stringify(state));
    say({
      ko: `저장했어요: 컬럼 ${state.columns.length}개, 정렬 ${state.sort.length}개, 스크롤 ${Math.round(state.scroll.top)}px`,
      en: `Saved: ${state.columns.length} columns, ${state.sort.length} sorts, scroll ${Math.round(state.scroll.top)}px`,
    });
  },
  load: (api) => say({
    ko: restore(api) ? '저장된 상태로 되돌렸어요.' : '저장된 상태가 없어요.',
    en: restore(api) ? 'Went back to the saved state.' : 'No saved state.',
  }),
  clear: (api) => {
    write(null);
    api.setColumnState(initial);
    api.setSortModel([]);
    api.setScroll({ top: 0, left: 0 });
    say({
      ko: '저장된 상태를 지우고 처음 모양으로 되돌렸어요.',
      en: 'Cleared the saved state and went back to the starting layout.',
    });
  },
  hideCity: (api) => api.setColumnVisible('city', false),
  pinName: (api) => api.pinColumn('name', 'start'),
  sortPrice: (api) => api.setSortModel([{ columnId: 'price', direction: 'desc' }]),
};

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="hideCity">Hide city</button>
    <button type="button" id="pinName">Pin name left</button>
    <button type="button" id="sortPrice">Price high to low</button>
    <button type="button" id="save">Save state</button>
    <button type="button" id="load">Restore saved</button>
    <button type="button" id="clear">Clear and reset</button>
  </div>
  <div id="grid" style="height: 340px"></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('hideCity').addEventListener('click', () => actions.hideCity(api));
document.getElementById('pinName').addEventListener('click', () => actions.pinName(api));
document.getElementById('sortPrice').addEventListener('click', () => actions.sortPrice(api));
document.getElementById('save').addEventListener('click', () => actions.save(api));
document.getElementById('load').addEventListener('click', () => actions.load(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
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 products = ['Wireless Earbuds', 'Laptop 14"', 'Smartwatch', 'Tablet 11"', 'Power Bank'];
const colors = ['Black', 'White', 'Silver', 'Navy', 'Pink'];
const rows = Array.from({ length: 60 }, (_, i) => ({
  id: i + 1,
  name: names[(i * 3) % names.length],
  city: cities[(i * 5) % cities.length],
  product: products[(i * 2 + (i >> 2)) % products.length],
  color: colors[(i * 7) % colors.length],
  quantity: 1 + ((i * 7) % 9),
  price: 29 + ((i * 7919) % 40) * 10,
}));
export const options = {
  columns: [
    { id: 'name', title: 'Name', width: 120 },
    { id: 'city', title: 'City', width: 90 },
    { id: 'product', title: 'Product', width: 150 },
    { id: 'color', title: 'Color', width: 90 },
    { id: 'quantity', title: 'Qty', kind: 'number', width: 80, align: 'end' },
    {
      id: 'price',
      title: 'Price',
      kind: 'number',
      width: 110,
      align: 'end',
      formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
    },
  ],
  rows,
  rowKey: 'id',
  rowHeight: 32,
};
const KEY = 'maxgrid-example-grid-state';
let say = () => { };
let initial = [];
let memory = null; // Where browser storage is unavailable (such as a preview), keep it in memory.
function read() {
  try {
    return localStorage.getItem(KEY) ?? memory;
  }
  catch {
    return memory;
  }
}
function write(text) {
  memory = text;
  try {
    if (text === null)
      localStorage.removeItem(KEY);
    else
      localStorage.setItem(KEY, text);
  }
  catch {
    say('Browser storage is unavailable here, so the state is remembered only until you close the page.');
  }
}
function restore(api) {
  const text = read();
  if (!text)
    return false;
  try {
    const state = JSON.parse(text);
    api.setColumnState(state.columns);
    api.setSortModel(state.sort);
    // Apply columns and sort first, then restore the scroll position after the screen has been redrawn.
    requestAnimationFrame(() => requestAnimationFrame(() => api.setScroll(state.scroll ?? { top: 0, left: 0 })));
    return true;
  }
  catch (error) {
    // A corrupt value must not freeze the screen. Report it and keep the default state.
    say(`Ignored the saved state because it is not valid: ${String(error)}`);
    return false;
  }
}
export function setup(api, log) {
  say = log;
  initial = api.getColumnState();
  log(restore(api)
    ? 'Saved state restored.'
    : 'No saved state. Drag a column or change a width, then press "Save state".');
}
export const actions = {
  save: (api) => {
    const state = {
      columns: api.getColumnState(),
      sort: api.getSortModel(),
      scroll: api.getScroll(),
    };
    write(JSON.stringify(state));
    say(`Saved: ${state.columns.length} columns, ${state.sort.length} sorts, scroll ${Math.round(state.scroll.top)}px`);
  },
  load: (api) => say(restore(api) ? 'Went back to the saved state.' : 'No saved state.'),
  clear: (api) => {
    write(null);
    api.setColumnState(initial);
    api.setSortModel([]);
    api.setScroll({ top: 0, left: 0 });
    say('Cleared the saved state and went back to the starting layout.');
  },
  hideCity: (api) => api.setColumnVisible('city', false),
  pinName: (api) => api.pinColumn('name', 'start'),
  sortPrice: (api) => api.setSortModel([{ columnId: 'price', direction: 'desc' }]),
};