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

페이지 번호를 주소창과 맞추기Keep the page in sync with the address

페이지를 넘길 때마다 주소 글자(?page=3&size=10)를 새로 적고, 주소가 바뀌면(뒤로 가기, 링크 열기) 그 값을 읽어 그 페이지로 돌려놓아요. 이 미리보기에서는 실제 주소창을 바꿀 수 없어서 '주소창' 줄이 대신 보여 줘요.On every page change the address text (?page=3&size=10) is rewritten, and when the address changes (back button, opened link) it is read back to restore the page. The preview cannot change the real address bar, so the address line stands in for it.

심화Advanced
직접 써 보기Live preview페이지 번호를 주소창과 맞추기Keep the page in sync with the address

코드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="back">뒤로 가기 흉내</button>
  </div>
  <div id="grid" style="height: 500px"></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('back').addEventListener('click', () => actions.back(api));
example.js
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
// 실제 페이지에서는 이 자리에 location.search를 써요. 예제는 갤러리 주소가 바뀌지 않도록 글자를 따로 들고 있어요.
let search = '?page=3&size=10';
function readQuery() {
  const params = new URLSearchParams(search);
  const page = Number(params.get('page'));
  const size = Number(params.get('size'));
  return {
    page: Number.isInteger(page) && page >= 1 ? page : 1,
    size: [10, 25].includes(size) ? size : 10,
  };
}
const initial = readQuery();
const PRODUCTS = [
  '무선 이어폰',
  '스마트 워치',
  '노트북 거치대',
  '보조배터리',
  '블루투스 스피커',
  '탁상 조명',
];
export const options = {
  columns: [
    { id: 'id', title: '번호', kind: 'number', width: 70 },
    { id: 'name', title: '품목', width: 200 },
  ],
  rows: Array.from({ length: 90 }, (_, i) => ({
    id: i + 1,
    name: `${PRODUCTS[i % PRODUCTS.length]} ${Math.floor(i / PRODUCTS.length) + 1}호`,
  })),
  rowKey: 'id',
  pagination: { mode: 'client', pageSize: initial.size, pageSizes: [10, 25], page: initial.page },
};
let bar = null;
const show = () => {
  if (bar)
    bar.textContent = L(`주소창: ${search}`, `Address bar: ${search}`);
};
// 그리드 → 주소: 페이지가 바뀌면 쿼리에 적어요. 주소 → 그리드: 주소에서 읽어 setPage로 돌려놓아요.
export function setup(api, log) {
  search = '?page=3&size=10';
  bar = document.createElement('div');
  bar.style.cssText = 'font: 13px ui-monospace, monospace; color: var(--muted); margin: 0 0 8px;';
  document.querySelector('.toolbar')?.insertAdjacentElement('afterend', bar);
  show();
  log({ ko: `처음 열린 주소: ${search}`, en: `Address when opened: ${search}` });
  const off = api.on('pageChanged', ({ page, pageSize }) => {
    search = `?page=${page}&size=${pageSize}`;
    // 실제 페이지에서는 여기서 history.replaceState(null, '', search)를 불러요.
    show();
    log({ ko: `주소가 바뀌었어요: ${search}`, en: `Address changed: ${search}` });
  });
  return () => {
    off();
    bar?.remove();
    bar = null;
  };
}
export const actions = {
  // 사용자가 브라우저 '뒤로 가기'를 눌러 주소가 ?page=7이 된 상황을 흉내 내요.
  back: (api) => {
    search = '?page=7&size=10';
    show();
    const { page, size } = readQuery();
    api.setPageSize(size);
    api.setPage(page);
  },
};

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="back">Simulate back</button>
  </div>
  <div id="grid" style="height: 500px"></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('back').addEventListener('click', () => actions.back(api));
example.js
// A real page would use location.search here. The example keeps the string separately so the gallery address does not change.
let search = '?page=3&size=10';
function readQuery() {
  const params = new URLSearchParams(search);
  const page = Number(params.get('page'));
  const size = Number(params.get('size'));
  return {
    page: Number.isInteger(page) && page >= 1 ? page : 1,
    size: [10, 25].includes(size) ? size : 10,
  };
}
const initial = readQuery();
const PRODUCTS = [
  'Wireless earbuds',
  'Smart watch',
  'Laptop stand',
  'Power bank',
  'Bluetooth speaker',
  'Desk lamp',
];
export const options = {
  columns: [
    { id: 'id', title: 'No.', kind: 'number', width: 70 },
    { id: 'name', title: 'Item', width: 220 },
  ],
  rows: Array.from({ length: 90 }, (_, i) => ({
    id: i + 1,
    name: `${PRODUCTS[i % PRODUCTS.length]} #${Math.floor(i / PRODUCTS.length) + 1}`,
  })),
  rowKey: 'id',
  pagination: { mode: 'client', pageSize: initial.size, pageSizes: [10, 25], page: initial.page },
};
let bar = null;
const show = () => {
  if (bar)
    bar.textContent = `Address bar: ${search}`;
};
// Grid -> address: when the page changes, write it to the query. Address -> grid: read it from the address and restore it with setPage.
export function setup(api, log) {
  search = '?page=3&size=10';
  bar = document.createElement('div');
  bar.style.cssText = 'font: 13px ui-monospace, monospace; color: var(--muted); margin: 0 0 8px;';
  document.querySelector('.toolbar')?.insertAdjacentElement('afterend', bar);
  show();
  log(`Address when opened: ${search}`);
  const off = api.on('pageChanged', ({ page, pageSize }) => {
    search = `?page=${page}&size=${pageSize}`;
    // A real page would call history.replaceState(null, '', search) here.
    show();
    log(`Address changed: ${search}`);
  });
  return () => {
    off();
    bar?.remove();
    bar = null;
  };
}
export const actions = {
  // Imitate the user pressing the browser Back button so the address becomes ?page=7.
  back: (api) => {
    search = '?page=7&size=10';
    show();
    const { page, size } = readQuery();
    api.setPageSize(size);
    api.setPage(page);
  },
};