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

자식을 쪽으로 나눠 불러오기: 더 보기Paged lazy children: Load more

treeChildrenPaging으로 폴더를 펼치면 첫 쪽만 오고, 아래 "더 보기" 줄을 눌러 다음 쪽을 받아요.With treeChildrenPaging a folder loads only its first page; press the "Load more" line below it for the next page.

심화Advanced
직접 써 보기Live preview자식을 쪽으로 나눠 불러오기: 더 보기Paged lazy children: Load more

코드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="loadMore">다음 쪽 받기(코드)</button>
    <button type="button" id="reload">처음부터 다시</button>
  </div>
  <div id="grid" style="height: 300px"></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('loadMore').addEventListener('click', () => actions.loadMore(api));
document.getElementById('reload').addEventListener('click', () => actions.reload(api));
example.js
// 맨 위 폴더만 처음에 있고, 폴더를 펼치면 treeChildrenPaging.load가 0쪽만 불러와요. 다음 쪽은 폴더 아래 "더 보기" 줄로 불러와요.
const folders = [
  { id: 'photos', parentId: null, name: '사진', folder: true, size: '' },
  { id: 'logs', parentId: null, name: '기록', folder: true, size: '' },
  { id: 'archive', parentId: null, name: '보관함', folder: true, size: '' },
];
// 서버가 폴더마다 가진 자식 수(실제로는 fetch가 이 자리에 와요).
const TOTALS = { photos: 23, logs: 120, archive: 45 };
const wait = (ms, signal) => new Promise((resolve, reject) => {
  const timer = setTimeout(resolve, ms);
  signal.addEventListener('abort', () => {
    clearTimeout(timer);
    reject(new DOMException('aborted', 'AbortError')); // 접으면 요청을 멈추고, 늦게 온 응답은 그리드가 버려요.
  });
});
export const options = {
  columns: [
    { id: 'name', title: '이름', width: 200 },
    { id: 'size', title: '크기', width: 80, align: 'end' },
  ],
  rows: folders,
  rowKey: 'id',
  tree: {
    parentKey: 'parentId',
    column: 'name',
    expandDepth: 0,
    hasChildren: (row) => row.folder,
  },
  treeChildrenPaging: {
    pageSize: 10,
    mode: 'more',
    load: async ({ parentKey, page, pageSize, signal }) => {
      await wait(450, signal);
      const total = TOTALS[String(parentKey)] ?? 0;
      const from = page * pageSize;
      const count = Math.max(0, Math.min(pageSize, total - from));
      return {
        total,
        rows: Array.from({ length: count }, (_, i) => ({
          id: `${String(parentKey)}-${from + i + 1}`,
          parentId: String(parentKey),
          name: `${String(parentKey)} ${from + i + 1}`,
          folder: false,
          size: `${(from + i + 1) * 12} KB`,
        })),
      };
    },
  },
};
export function setup(api, log) {
  api.on('treeChildrenLoaded', (e) => log({
    ko: `${String(e.parentKey)}: ${e.page + 1}쪽을 받았어요(${e.count}개).`,
    en: `${String(e.parentKey)}: page ${e.page + 1} loaded (${e.count} rows).`,
  }));
  api.on('treeChildrenError', (e) => log({
    ko: `${String(e.parentKey)}: ${e.page + 1}쪽 오류: ${e.message}`,
    en: `${String(e.parentKey)}: page ${e.page + 1} problem: ${e.message}`,
  }));
  log({
    ko: '폴더를 펼치면 10개만 와요. 맨 아래 "더 보기"를 눌러 다음 쪽을 받아요. 접었다 펼쳐도 다시 받지 않아요.',
    en: 'Open a folder and only 10 rows arrive. Press "Load more" at the bottom for the next page. Collapsing and reopening does not fetch again.',
  });
}
export const actions = {
  reload: (api) => api.reloadTreeChildren('photos'),
  loadMore: (api) => {
    if (api.getTreeChildrenState('photos').hasMore)
      api.loadMoreTreeChildren('photos');
  },
};

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="loadMore">Load next page (code)</button>
    <button type="button" id="reload">Reload</button>
  </div>
  <div id="grid" style="height: 300px"></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('loadMore').addEventListener('click', () => actions.loadMore(api));
document.getElementById('reload').addEventListener('click', () => actions.reload(api));
example.js
// Only the top folders exist at first. Opening a folder makes treeChildrenPaging.load fetch page 0 only; the next pages come from the "Load more" line under the folder.
const folders = [
  { id: 'photos', parentId: null, name: 'Photos', folder: true, size: '' },
  { id: 'logs', parentId: null, name: 'Logs', folder: true, size: '' },
  { id: 'archive', parentId: null, name: 'Archive', folder: true, size: '' },
];
// How many children the server has per folder (real code would call fetch here).
const TOTALS = { photos: 23, logs: 120, archive: 45 };
const wait = (ms, signal) => new Promise((resolve, reject) => {
  const timer = setTimeout(resolve, ms);
  signal.addEventListener('abort', () => {
    clearTimeout(timer);
    reject(new DOMException('aborted', 'AbortError')); // Collapsing stops the request and the grid drops a late response.
  });
});
export const options = {
  columns: [
    { id: 'name', title: 'Name', width: 200 },
    { id: 'size', title: 'Size', width: 80, align: 'end' },
  ],
  rows: folders,
  rowKey: 'id',
  tree: {
    parentKey: 'parentId',
    column: 'name',
    expandDepth: 0,
    hasChildren: (row) => row.folder,
  },
  treeChildrenPaging: {
    pageSize: 10,
    mode: 'more',
    load: async ({ parentKey, page, pageSize, signal }) => {
      await wait(450, signal);
      const total = TOTALS[String(parentKey)] ?? 0;
      const from = page * pageSize;
      const count = Math.max(0, Math.min(pageSize, total - from));
      return {
        total,
        rows: Array.from({ length: count }, (_, i) => ({
          id: `${String(parentKey)}-${from + i + 1}`,
          parentId: String(parentKey),
          name: `${String(parentKey)} ${from + i + 1}`,
          folder: false,
          size: `${(from + i + 1) * 12} KB`,
        })),
      };
    },
  },
};
export function setup(api, log) {
  api.on('treeChildrenLoaded', (e) => log(`${String(e.parentKey)}: page ${e.page + 1} loaded (${e.count} rows).`));
  api.on('treeChildrenError', (e) => log(`${String(e.parentKey)}: page ${e.page + 1} problem: ${e.message}`));
  log('Open a folder and only 10 rows arrive. Press "Load more" at the bottom for the next page. Collapsing and reopening does not fetch again.');
}
export const actions = {
  reload: (api) => api.reloadTreeChildren('photos'),
  loadMore: (api) => {
    if (api.getTreeChildrenState('photos').hasMore)
      api.loadMoreTreeChildren('photos');
  },
};