React Table with Sorting
Revision History
No revision history recorded yet.
import { useState, useMemo } from 'react';
export default function SortableTable({ columns, data }) {
const [sort, setSort] = useState({ key: null, dir: 'asc' });
const sorted = useMemo(() => {
if (!sort.key) return data;
return [...data].sort((a, b) => {
const va = a[sort.key], vb = b[sort.key];
const cmp = va < vb ? -1 : va > vb ? 1 : 0;
return sort.dir === 'asc' ? cmp : -cmp;
});
}, [data, sort]);
const toggle = (key) => setSort(s =>
s.key === key ? { key, dir: s.dir === 'asc' ? 'desc' : 'asc' } : { key, dir: 'asc' }
);
return (
<table>
<thead>
<tr>
{columns.map(col => (
<th key={col.key} onClick={() => toggle(col.key)} style={{ cursor: 'pointer' }}>
{col.label} {sort.key === col.key ? (sort.dir === 'asc' ? '↑' : '↓') : ''}
</th>
))}
</tr>
</thead>
<tbody>
{sorted.map((row, i) => (
<tr key={i}>
{columns.map(col => <td key={col.key}>{row[col.key]}</td>)}
</tr>
))}
</tbody>
</table>
);
}