Quick Start (Next.js)

  1. สร้างโปรเจกต์และติดตั้งแพ็กเกจ ต้องใช้ Node.js 22 ขึ้นไป (ข้ามขั้นสร้างโปรเจกต์ได้ถ้ามีอยู่แล้ว)
    npx create-next-app@latest my-app --ts --app
    cd my-app
    npm install @siampiwat/spgrid
  2. สร้าง client component ที่ app/Grid.tsx SPGrid ทำงานกับ DOM จึงห้าม import บน server ให้ import แบบ dynamic ใน useEffect และเรียก destroy() ตอน unmount
    'use client';
    
    import { useEffect, useRef } from 'react';
    
    type Row = { id: number; name: string; status: string };
    
    export default function Grid({ rows }: { rows: Row[] }) {
      const el = useRef<HTMLDivElement>(null);
      const grid = useRef<{ setRows(rows: Row[]): void; destroy(): void } | null>(null);
    
      useEffect(() => {
        let cancelled = false;
        import('@siampiwat/spgrid').then(({ SPGrid }) => {
          if (cancelled || !el.current) return;
          grid.current = new SPGrid(el.current, {
            rowKey: 'id',
            columns: [
              { key: 'id', label: 'ID', sortable: true },
              { key: 'name', label: 'Name', sortable: true },
              { key: 'status', label: 'Status', type: 'badge', badges: { open: { tone: 'success' } } },
            ],
            rows,
            searchable: true,
            pageSize: 10,
          });
        });
        return () => {
          cancelled = true;
          grid.current?.destroy();
          grid.current = null;
        };
        // eslint-disable-next-line react-hooks/exhaustive-deps
      }, []);
    
      useEffect(() => {
        grid.current?.setRows(rows); // คง sort / filter / หน้าปัจจุบันไว้
      }, [rows]);
    
      return <div ref={el} />;
    }
  3. เรียกใช้ใน page แล้วรัน ที่ app/page.tsx จากนั้นรัน npm run dev และเปิด http://localhost:3000
    import Grid from './Grid';
    
    const rows = [
      { id: 1, name: 'Ada', status: 'open' },
      { id: 2, name: 'Grace', status: 'closed' },
      { id: 3, name: 'Linus', status: 'open' },
    ];
    
    export default function Home() {
      return <Grid rows={rows} />;
    }