สร้าง 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} />;
}
เรียกใช้ใน 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} />;
}