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

폴더를 열 때 안쪽을 가져오기Fetch a folder's contents when it opens

처음에는 맨 위 줄만 보여 주고, 폴더를 처음 열 때 그 폴더의 내용만 서버에서 받아 와요. 비어 있는 폴더나 응답이 실패한 폴더도 알맞게 보여 줘요.Only the top rows load at first; a folder's contents are fetched the first time it opens. Empty folders and failed requests are handled too.

활용Intermediate
직접 써 보기Live preview폴더를 열 때 안쪽을 가져오기Fetch a folder's contents when it opens

코드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="openDocs">"문서" 열기</button>
    <button type="button" id="openPhotos">"사진" 열기</button>
    <button type="button" id="openEmpty">"빈 폴더" 열기</button>
    <button type="button" id="openFlaky">"불안정한 폴더" 열기</button>
    <button type="button" id="closeFlaky">"불안정한 폴더" 닫기</button>
    <button type="button" id="collapseAll">모두 닫기</button>
  </div>
  <div id="grid" style="height: 362px"></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('openDocs').addEventListener('click', () => actions.openDocs(api));
document.getElementById('openPhotos').addEventListener('click', () => actions.openPhotos(api));
document.getElementById('openEmpty').addEventListener('click', () => actions.openEmpty(api));
document.getElementById('openFlaky').addEventListener('click', () => actions.openFlaky(api));
document.getElementById('closeFlaky').addEventListener('click', () => actions.closeFlaky(api));
document.getElementById('collapseAll').addEventListener('click', () => actions.collapseAll(api));
example.js
// 처음에는 맨 위 줄만 있어요. 폴더를 처음 열 때 loadChildren이 불려서 그 폴더의 내용만 가져와요.
const topRows = [
  { id: 'docs', parentId: null, name: '문서', folder: true, type: '폴더' },
  { id: 'photos', parentId: null, name: '사진', folder: true, type: '폴더' },
  { id: 'empty', parentId: null, name: '빈 폴더', folder: true, type: '폴더' },
  { id: 'flaky', parentId: null, name: '불안정한 폴더', folder: true, type: '폴더' },
  { id: 'memo', parentId: null, name: '메모.txt', folder: false, type: '파일' },
];
// 서버가 폴더마다 돌려줄 내용이에요. 실제로는 fetch(...)로 받는 자리예요.
const folders = {
  docs: [
    ['보고서', true],
    ['계약서.pdf', false],
    ['회의록.docx', false],
  ],
  reports: [
    ['월간 보고.xlsx', false],
    ['분기 보고.pptx', false],
  ],
  photos: [
    ['여행 1.jpg', false],
    ['여행 2.jpg', false],
    ['가족.png', false],
    ['로고.svg', false],
  ],
  flaky: [['복구된 파일.txt', false]],
};
let flakyTries = 0;
export const options = {
  columns: [
    { id: 'name', title: '이름', width: 220 },
    { id: 'type', title: '종류', width: 80 },
  ],
  rows: topRows,
  rowKey: 'id',
  tree: {
    parentKey: 'parentId',
    column: 'name',
    hasChildren: (row) => row.folder, // 폴더만 화살표가 생겨요.
    loadChildren: async (row, { key, signal }) => {
      await new Promise((resolve) => setTimeout(resolve, 700)); // 서버 응답을 기다리는 시간
      if (signal.aborted)
        return []; // 기다리다 접으면 이 응답은 그리드가 버려요.
      if (row.id === 'flaky' && flakyTries++ === 0)
        throw new Error('서버가 응답하지 않아요');
      const id = row.name === '보고서' ? 'reports' : String(key);
      return (folders[id] ?? []).map(([name, folder], i) => ({
        id: `${row.id}-${i}`,
        parentId: String(key),
        name,
        folder,
        type: folder ? '폴더' : '파일',
      }));
    },
  },
};
const says = {
  loading: ['불러오는 중이에요…', 'Loading…'],
  loaded: ['불러왔어요', 'Loaded'],
  error: [
    '불러오지 못했어요. 접었다가 다시 열면 한 번 더 시도해요.',
    'Could not load. Collapse and open it again to retry once more.',
  ],
  cancelled: [
    '기다리다 접어서 응답을 버렸어요',
    'Collapsed while waiting, so the response was dropped',
  ],
};
export function setup(api, log) {
  return api.on('childrenLoadChanged', ({ rowKey, state, count }) => {
    const name = api.getRowByKey(rowKey)?.name ?? String(rowKey);
    log({
      ko: `${name}: ${says[state]?.[0] ?? state}${count === undefined ? '' : ` (${count}개)`}`,
      en: `${name}: ${says[state]?.[1] ?? state}${count === undefined ? '' : ` (${count})`}`,
    });
  });
}
export const actions = {
  openDocs: (api) => api.expandRow('docs'),
  openPhotos: (api) => api.expandRow('photos'),
  // 이미 불러와 보니 비어 있던 폴더는 다시 펼칠 수 없어서 오류가 나요. 처음 한 번의 결과는 기록에 나와요.
  openEmpty: (api) => {
    try {
      api.expandRow('empty');
    }
    catch {
      // 이미 "불러옴 (0개)"로 기록에 나왔어요. 펼칠 것이 없어요.
    }
  },
  openFlaky: (api) => api.expandRow('flaky'),
  closeFlaky: (api) => api.collapseRow('flaky'),
  collapseAll: (api) => api.collapseAll(),
};

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="openDocs">Open "Documents"</button>
    <button type="button" id="openPhotos">Open "Photos"</button>
    <button type="button" id="openEmpty">Open "Empty folder"</button>
    <button type="button" id="openFlaky">Open "Flaky folder"</button>
    <button type="button" id="closeFlaky">Close "Flaky folder"</button>
    <button type="button" id="collapseAll">Collapse all</button>
  </div>
  <div id="grid" style="height: 362px"></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('openDocs').addEventListener('click', () => actions.openDocs(api));
document.getElementById('openPhotos').addEventListener('click', () => actions.openPhotos(api));
document.getElementById('openEmpty').addEventListener('click', () => actions.openEmpty(api));
document.getElementById('openFlaky').addEventListener('click', () => actions.openFlaky(api));
document.getElementById('closeFlaky').addEventListener('click', () => actions.closeFlaky(api));
document.getElementById('collapseAll').addEventListener('click', () => actions.collapseAll(api));
example.js
// At first there are only the top rows. The first time a folder opens, loadChildren is called and fetches only that folder's contents.
const topRows = [
  { id: 'docs', parentId: null, name: 'Documents', folder: true, type: 'Folder' },
  { id: 'photos', parentId: null, name: 'Photos', folder: true, type: 'Folder' },
  { id: 'empty', parentId: null, name: 'Empty folder', folder: true, type: 'Folder' },
  { id: 'flaky', parentId: null, name: 'Flaky folder', folder: true, type: 'Folder' },
  { id: 'memo', parentId: null, name: 'memo.txt', folder: false, type: 'File' },
];
// The contents the server would return for each folder. In real code this is where fetch(...) goes.
const folders = {
  docs: [
    ['Reports', true],
    ['contract.pdf', false],
    ['minutes.docx', false],
  ],
  reports: [
    ['monthly-report.xlsx', false],
    ['quarterly-report.pptx', false],
  ],
  photos: [
    ['trip-1.jpg', false],
    ['trip-2.jpg', false],
    ['family.png', false],
    ['logo.svg', false],
  ],
  flaky: [['recovered-file.txt', false]],
};
let flakyTries = 0;
export const options = {
  columns: [
    { id: 'name', title: 'Name', width: 220 },
    { id: 'type', title: 'Type', width: 80 },
  ],
  rows: topRows,
  rowKey: 'id',
  tree: {
    parentKey: 'parentId',
    column: 'name',
    hasChildren: (row) => row.folder, // Only folders get an arrow.
    loadChildren: async (row, { key, signal }) => {
      await new Promise((resolve) => setTimeout(resolve, 700)); // Time spent waiting for the server
      if (signal.aborted)
        return []; // If it was collapsed while waiting, the grid drops this response.
      if (row.id === 'flaky' && flakyTries++ === 0)
        throw new Error('The server is not responding');
      const id = row.name === 'Reports' ? 'reports' : String(key);
      return (folders[id] ?? []).map(([name, folder], i) => ({
        id: `${row.id}-${i}`,
        parentId: String(key),
        name,
        folder,
        type: folder ? 'Folder' : 'File',
      }));
    },
  },
};
const says = {
  loading: 'Loading…',
  loaded: 'Loaded',
  error: 'Could not load. Collapse and open it again to retry once more.',
  cancelled: 'Collapsed while waiting, so the response was dropped',
};
export function setup(api, log) {
  return api.on('childrenLoadChanged', ({ rowKey, state, count }) => {
    const name = api.getRowByKey(rowKey)?.name ?? String(rowKey);
    log(`${name}: ${says[state] ?? state}${count === undefined ? '' : ` (${count})`}`);
  });
}
export const actions = {
  openDocs: (api) => api.expandRow('docs'),
  openPhotos: (api) => api.expandRow('photos'),
  // A folder that turned out empty when loaded cannot be expanded again, so this throws. The result of the first attempt appears in the log.
  openEmpty: (api) => {
    try {
      api.expandRow('empty');
    }
    catch {
      // Already logged as "Loaded (0)". There is nothing to expand.
    }
  },
  openFlaky: (api) => api.expandRow('flaky'),
  closeFlaky: (api) => api.collapseRow('flaky'),
  collapseAll: (api) => api.collapseAll(),
};