Skip to content
This repository has been archived by the owner on Oct 2, 2024. It is now read-only.

Commit

Permalink
Derive item key from sorted or first header. + bump patch version
Browse files Browse the repository at this point in the history
Dont depend on table data having id key
  • Loading branch information
sverhoeven committed Feb 16, 2024
1 parent 0c389b0 commit 2d83f9c
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
"access": "public"
},
"license": "Apache-2.0",
"version": "0.4.0",
"version": "0.4.1",
"type": "module",
"files": [
"dist"
Expand Down
26 changes: 21 additions & 5 deletions src/components/SortableTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ export interface Stats {
}

export interface DataItem {
id: number;
[key: string]: number | string | Stats;
}

Expand Down Expand Up @@ -133,6 +132,14 @@ interface SortState {

type Orientation = "top" | "left";

function itemKeyFinder(item: DataItem, itemKey: string) {
const value = item[itemKey];
if (typeof value === "object") {
return value.mean.toString();
}
return value.toString();
}

export function SortableTable({
orientation = "top",
headers,
Expand All @@ -144,8 +151,11 @@ export function SortableTable({
data: DataItem[];
className: string;
}) {
const initialSortedHeader = headers.find((h) => h.sorted !== undefined);
// use the first header if no header is sorted as key for a data item
const itemKey = (initialSortedHeader ?? headers[0]).key;

const [sortState, setSortState] = useState<SortState>(() => {
const initialSortedHeader = headers.find((h) => h.sorted !== undefined);
if (initialSortedHeader && initialSortedHeader.sorted !== undefined) {
return {
key: initialSortedHeader.key,
Expand Down Expand Up @@ -204,9 +214,12 @@ export function SortableTable({
</thead>
<tbody>
{sortedData.map((row) => (
<tr key={row.id} className="table-item">
<tr key={itemKeyFinder(row, itemKey)} className="table-item">
{headers.map((header) => (
<td key={`${row.id}-${header.key}`} className="table-cell">
<td
key={`${itemKeyFinder(row, itemKey)}-${header.key}`}
className="table-cell"
>
<CellContent
data={row}
header={header}
Expand Down Expand Up @@ -237,7 +250,10 @@ export function SortableTable({
orientation={orientation}
/>
{sortedData.map((col) => (
<td key={`${col.id}-${header.key}`} className="table-cell">
<td
key={`${itemKeyFinder(col, itemKey)}-${header.key}`}
className="table-cell"
>
<CellContent
data={col}
header={header}
Expand Down

0 comments on commit 2d83f9c

Please sign in to comment.