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

자식을 쪽으로 나눠 불러오기: 스크롤하면 저절로Paged lazy children: infinite scroll

mode: 'infinite'면 "더 보기" 줄이 화면 가까이 오면 다음 쪽을 저절로 불러와요.With mode: 'infinite' the next page loads by itself when the "Load more" line comes near the viewport.

심화Advanced
직접 써 보기Live preview자식을 쪽으로 나눠 불러오기: 스크롤하면 저절로Paged lazy children: infinite scroll

코드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="reload">처음부터 다시</button>
  </div>
  <div id="grid" style="height: 260px"></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('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: 15,
    mode: 'infinite',
    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: '"기록" 폴더를 펼치고 아래로 스크롤해 보세요. "더 보기" 줄이 3줄 안으로 가까워지면 다음 쪽이 저절로 와요(120개).',
    en: 'Open the "Logs" folder and scroll down. When the "Load more" line comes within 3 rows the next page loads by itself (120 rows).',
  });
}
export const actions = {
  reload: (api) => api.reloadTreeChildren('logs'),
};

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="reload">Reload</button>
  </div>
  <div id="grid" style="height: 260px"></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('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: 15,
    mode: 'infinite',
    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 the "Logs" folder and scroll down. When the "Load more" line comes within 3 rows the next page loads by itself (120 rows).');
}
export const actions = {
  reload: (api) => api.reloadTreeChildren('logs'),
};