Tanstack table for svelte

310 views Asked by At

I am using tankstack table in my svelte project. I want to add checkbox to select the row in the table. How can i do it?

i checked react example but could not figure how to do it for svelte. Has someone tried it or has any idea how to do it?

1

There are 1 answers

0
Olly On

I was struggling with this myself, and have come up with the following solution.

First, create a RowCheckBox.svelte component:

<script lang="ts">
    export let checked, indeterminate, onChange;
</script>

<input class="checkbox" type="checkbox" on:change={onChange} {checked} bind:indeterminate={indeterminate}/>

Next, define your column's as normal, passing in the following items we'll need in the component as well as your object type. For context, I have a custom Child type defined in my project.

const defaultColumns: ColumnDef<Child>[] = [
    {
        id: 'select',
        header: ({table}) => renderComponent(RowCheckBox, {
            checked: table.getIsAllRowsSelected(),
            indeterminate: table.getIsSomeRowsSelected(),
            onChange: table.getToggleAllRowsSelectedHandler(),
        }),
        cell: (props) => renderComponent(RowCheckBox, {
            checked: props.row.getIsSelected(),
            disabled: !props.row.getCanSelect(),
            indeterminate: props.row.getIsSomeSelected(),
            onChange: props.row.getToggleSelectedHandler(),
        })

    },
    // Rest of Columns
]

Before we create our table, we need to handle ticking a checkbox by defining a state object and a function to handle updates. This is indirectly passed along to the component, through TanStack via on:change={onChange}.

let selection: RowSelectionState = {};

const onSelect = (updater: any) => {
    if (updater instanceof Function) {
        selection = updater(selection);
    } else {
        selection = updater;
    }

    options.update((old) => ({
        ...old,
        state: {
            ...old.state,
            rowSelection: selection,
        },
    } as TableOptions<Child>));
}

Finally this can all be passed into table options:

const options = writable<TableOptions<Child>>({
    //... other options
    columns: defaultColumns,
    state: {
        //... other state
        rowSelection: selection,
    },
    enableRowSelection: true,
    onRowSelectionChange: onSelect,
    //... other options
})