Skip to content

Instantly share code, notes, and snippets.

@thehackermonkey
Created December 11, 2023 20:45
Show Gist options
  • Save thehackermonkey/97352a491eb205e8e396e0fd87d6a008 to your computer and use it in GitHub Desktop.
Save thehackermonkey/97352a491eb205e8e396e0fd87d6a008 to your computer and use it in GitHub Desktop.
Display custom Svelte components using TanStack Table
<script>
// your custom component using a Badge for demo
import Badge from '@/components/Badge.svelte'
// renderComponent is the magic
import {
createSvelteTable,
createColumnHelper,
renderComponent,
flexRender,
getCoreRowModel,
} from '@tanstack/svelte-table'
const data = yourFetch();
const columnHelper = createColumnHelper();
const options = {
data,
columns: [
// ... your columns
columnHelper.accessor(row => row.status, {
id: 'status',
cell: (cell) => {
const status = cell.getValue();
// render your custom component with the data
// or custom render a value based on data
return renderComponent(Badge, {
// pass props
label: status === 'pending' ? 'Pending confirmation' : 'Ready',
class: status === 'pending' ? 'badge-warning' : 'badge-success'
})
}
}),
],
getCoreRowModel: getCoreRowModel(),
}
const table = createSvelteTable(options);
</script>
<table class="table table-fixed">
<thead>
{#each $table.getHeaderGroups() as headerGroup}
<tr>
{#each headerGroup.headers as header}
<th class="font-bold bg-base-200">
{#if !header.isPlaceholder}
<svelte:component
this={flexRender(
header.column.columnDef.header,
header.getContext()
)}
/>
{/if}
</th>
{/each}
</tr>
{/each}
</thead>
<tbody>
{#each $table.getRowModel().rows as row}
<tr>
{#each row.getVisibleCells() as cell}
<td>
<svelte:component
this={flexRender(cell.column.columnDef.cell, cell.getContext())}
/>
</td>
{/each}
</tr>
{/each}
</tbody>
<tfoot>
{#each $table.getFooterGroups() as footerGroup}
<tr>
{#each footerGroup.headers as header}
<th>
{#if !header.isPlaceholder}
<svelte:component
this={flexRender(
header.column.columnDef.footer,
header.getContext()
)}
/>
{/if}
</th>
{/each}
</tr>
{/each}
</tfoot>
</table>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment