import React, { useState } from "react"; interface DataTableProps { data: unknown; } export function DataTable({ data }: DataTableProps) { const [sortKey, setSortKey] = useState(null); const [sortDir, setSortDir] = useState<"asc" | "desc">("asc"); if (!Array.isArray(data) || data.length === 0) { return
No data
; } const first = data[0]; if (typeof first !== "object" || first === null) { return
Data is not tabular
; } const keys = Object.keys(first); const sortedData = sortKey ? [...data].sort((a, b) => { const aVal = (a as Record)[sortKey]; const bVal = (b as Record)[sortKey]; const cmp = aVal < bVal ? -1 : aVal > bVal ? 1 : 0; return sortDir === "asc" ? cmp : -cmp; }) : data; const handleSort = (key: string) => { if (sortKey === key) { setSortDir(sortDir === "asc" ? "desc" : "asc"); } else { setSortKey(key); setSortDir("asc"); } }; const formatCell = (value: unknown): string => { if (value === null || value === undefined) return ""; if (typeof value === "object") return JSON.stringify(value); return String(value); }; return (
{keys.map((key) => ( ))} {sortedData.map((row, i) => ( {keys.map((key) => ( ))} ))}
handleSort(key)}> {key} {sortKey === key ? (sortDir === "asc" ? " ▲" : " ▼") : ""}
{formatCell((row as Record)[key])}
); }