Skip to content

Usage

A table needs two things: columns and data.

Basic.svelte
<script lang="ts">
import { MaterialSvelteTable, type MRT_ColumnDef } from 'material-svelte-tanstack-table';
import { type Person, makeData } from '../data/makeData';
// Columns and data should be stable, so define them once.
const columns: MRT_ColumnDef<Person>[] = [
{ accessorKey: 'firstName', header: 'First Name' },
{ accessorKey: 'lastName', header: 'Last Name' },
{ accessorKey: 'email', header: 'Email', size: 260 },
{ accessorKey: 'state', header: 'State' },
{ accessorKey: 'age', header: 'Age', size: 100 },
];
const data = makeData(60);
</script>
<MaterialSvelteTable options={{ columns, data }} />

Each column needs a header and either an accessorKey (a key of your row, with dot notation for nested data) or an accessorFn plus an id. Define columns once, outside any reactive code, so they stay stable. See Data Columns.

The table is created once. Anything that changes over time must be passed as a getter, or the table keeps the first value forever:

<script lang="ts">
let data = $state<Person[]>([]);
let isLoading = $state(true);
</script>
<MaterialSvelteTable
options={{
columns,
// reactive: a getter
get data() {
return data;
},
state: {
get isLoading() {
return isLoading;
},
},
// not reactive: a plain value is fine
enableRowSelection: true,
}}
/>

<MaterialSvelteTable options={...} /> creates a table for you. When you need the instance, for example to start creating a row from a button, or to read the selected rows, create it yourself and pass it in:

<script lang="ts">
import { MaterialSvelteTable, createMaterialSvelteTable } from 'material-svelte-tanstack-table';
const table = createMaterialSvelteTable({ columns, data });
</script>
<button onclick={() => table.resetColumnFilters(true)}>Clear filters</button>
<MaterialSvelteTable {table} />

createMaterialSvelteTable registers effects, so call it while a component is initializing.

The instance is a TanStack Table v9 table plus a few MRT additions:

MemberWhat it is
table.mrtStateThe state MRT owns: density, isFullScreen, editingRow, creatingRow, isLoading, …
table.atoms.<slice>TanStack state, e.g. table.atoms.sorting.get(). Reads are reactive in templates.
table.setDensity, table.setCreatingRow, …Setters for the MRT state.
table.userOptionsThe options as you passed them.