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

서버가 그린 HTML 표를 그리드로 바꾸기Turn a server-rendered HTML table into a grid

서버가 이미 그려 준 평범한 HTML 표를 읽어서 컬럼과 행으로 바꾸면, 정렬·필터 같은 기능을 그대로 쓸 수 있어요. 머리글 칸에 적어 둔 이름표로 항목 이름과 숫자 여부를 알려 줘요.Read a plain server-rendered HTML table into columns and rows and sorting and filtering work right away. Labels written on the header cells tell the field names and which are numbers.

활용Intermediate
직접 써 보기Live preview서버가 그린 HTML 표를 그리드로 바꾸기Turn a server-rendered HTML table into a grid

코드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 id="grid" style="height: 520px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api);
example.js
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
// 서버가 이미 그려 주는 평범한 HTML 표예요. data-key는 필드 이름, data-kind는 숫자 표시고요.
// 실제 페이지에서는 이 글자 대신 document.querySelector('table')을 읽으면 돼요.
const TABLE_HTML = `
<table>
  <thead>
  <tr>
    <th data-key="id" data-kind="number">번호</th>
    <th data-key="product">품명</th>
    <th data-key="stock" data-kind="number">재고</th>
    <th data-key="price" data-kind="number">단가(원)</th>
    <th data-key="supplier">공급사</th>
  </tr>
  </thead>
  <tbody>
  <tr><td>1</td><td>스탠드 조명</td><td>1,240</td><td>18,900</td><td>한빛물류</td></tr>
  <tr><td>2</td><td>모니터 받침대</td><td>380</td><td>32,500</td><td>북극성무역</td></tr>
  <tr><td>3</td><td>기계식 키보드</td><td>95</td><td>89,000</td><td>한빛물류</td></tr>
  <tr><td>4</td><td>케이블 정리함</td><td>2,610</td><td>4,200</td><td>다온상사</td></tr>
  </tbody>
</table>`;
function fromTable(html) {
  const table = new DOMParser().parseFromString(html, 'text/html').querySelector('table');
  if (!table)
    throw new Error('<table>을 찾지 못했어요');
  const heads = Array.from(table.querySelectorAll('thead th'));
  const columns = heads.map((th) => ({
    id: th.dataset.key ?? '',
    title: th.textContent?.trim() ?? '',
    kind: th.dataset.kind === 'number' ? 'number' : 'text',
    align: th.dataset.kind === 'number' ? 'end' : 'start',
    ...(th.dataset.kind === 'number'
      ? { formatValue: (value) => Number(value).toLocaleString('ko-KR') }
      : {}),
  }));
  const rows = Array.from(table.querySelectorAll('tbody tr')).map((tr) => {
    const cells = Array.from(tr.querySelectorAll('td'));
    return Object.fromEntries(columns.map((column, index) => {
      const text = cells[index]?.textContent?.trim() ?? '';
      return [column.id, column.kind === 'number' ? Number(text.replaceAll(',', '')) : text];
    }));
  });
  return { columns, rows, rowKey: 'id' };
}
export const options = fromTable(TABLE_HTML);
// 변환하는 원본 HTML 표를 그리드 위에 그대로 보여 줘요(내가 위에 적어 둔 고정 글자라서 안전해요).
export function setup() {
  const grid = document.querySelector('.mxg');
  const wrap = document.createElement('div');
  wrap.style.cssText = 'margin: 0 0 10px; font-size: 12px; color: var(--muted);';
  const label = document.createElement('div');
  label.textContent = L('서버가 보낸 HTML 표 (이 표를 아래 그리드로 바꿨어요)', 'HTML table sent by the server (turned into the grid below)');
  label.style.cssText = 'margin: 0 0 4px; font-weight: 600;';
  const holder = document.createElement('div');
  holder.innerHTML = TABLE_HTML;
  const table = holder.querySelector('table');
  if (table)
    table.style.cssText = 'border-collapse: collapse; width: 100%; font-size: 12px;';
  for (const cell of holder.querySelectorAll('th, td')) {
    cell.style.cssText = 'border: 1px solid var(--line); padding: 2px 6px; text-align: left;';
  }
  wrap.append(label, holder);
  grid?.insertAdjacentElement('beforebegin', wrap);
  return () => wrap.remove();
}

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 id="grid" style="height: 520px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api);
example.js
// An ordinary HTML table the server already renders. data-key is the field name and data-kind marks a number.
// In a real page, read document.querySelector('table') instead of this text.
const TABLE_HTML = `
<table>
  <thead>
  <tr>
    <th data-key="id" data-kind="number">No.</th>
    <th data-key="product">Product</th>
    <th data-key="stock" data-kind="number">Stock</th>
    <th data-key="price" data-kind="number">Unit price ($)</th>
    <th data-key="supplier">Supplier</th>
  </tr>
  </thead>
  <tbody>
  <tr><td>1</td><td>Desk lamp</td><td>1,240</td><td>18,900</td><td>Northwind Logistics</td></tr>
  <tr><td>2</td><td>Monitor stand</td><td>380</td><td>32,500</td><td>Polaris Trading</td></tr>
  <tr><td>3</td><td>Mechanical keyboard</td><td>95</td><td>89,000</td><td>Northwind Logistics</td></tr>
  <tr><td>4</td><td>Cable organizer</td><td>2,610</td><td>4,200</td><td>Harmony Supply</td></tr>
  </tbody>
</table>`;
function fromTable(html) {
  const table = new DOMParser().parseFromString(html, 'text/html').querySelector('table');
  if (!table)
    throw new Error('Could not find <table>');
  const heads = Array.from(table.querySelectorAll('thead th'));
  const columns = heads.map((th) => ({
    id: th.dataset.key ?? '',
    title: th.textContent?.trim() ?? '',
    kind: th.dataset.kind === 'number' ? 'number' : 'text',
    align: th.dataset.kind === 'number' ? 'end' : 'start',
    ...(th.dataset.kind === 'number'
      ? { formatValue: (value) => Number(value).toLocaleString('en-US') }
      : {}),
  }));
  const rows = Array.from(table.querySelectorAll('tbody tr')).map((tr) => {
    const cells = Array.from(tr.querySelectorAll('td'));
    return Object.fromEntries(columns.map((column, index) => {
      const text = cells[index]?.textContent?.trim() ?? '';
      return [column.id, column.kind === 'number' ? Number(text.replaceAll(',', '')) : text];
    }));
  });
  return { columns, rows, rowKey: 'id' };
}
export const options = fromTable(TABLE_HTML);
// Show the source HTML table being converted as is above the grid (safe because it is a fixed string written above).
export function setup() {
  const grid = document.querySelector('.mxg');
  const wrap = document.createElement('div');
  wrap.style.cssText = 'margin: 0 0 10px; font-size: 12px; color: var(--muted);';
  const label = document.createElement('div');
  label.textContent = 'HTML table sent by the server (turned into the grid below)';
  label.style.cssText = 'margin: 0 0 4px; font-weight: 600;';
  const holder = document.createElement('div');
  holder.innerHTML = TABLE_HTML;
  const table = holder.querySelector('table');
  if (table)
    table.style.cssText = 'border-collapse: collapse; width: 100%; font-size: 12px;';
  for (const cell of holder.querySelectorAll('th, td')) {
    cell.style.cssText = 'border: 1px solid var(--line); padding: 2px 6px; text-align: left;';
  }
  wrap.append(label, holder);
  grid?.insertAdjacentElement('beforebegin', wrap);
  return () => wrap.remove();
}