V9 / Svelte 5: How to make Row Selection Work? #5857
-
main problem I see is that my table is not displaying the checked state correctly when using check all, I have seen this example, but couldn't make it to work with latest versions. Also ideally I would like to use my custom checkbox component (generated with shadcn) {
id: 'select',
header: ({ table }) =>
renderComponent(Checkbox, {
'aria-label': 'Select all Rows',
checked: table.getIsAllRowsSelected(),
indeterminate: table.getIsSomeRowsSelected(),
onCheckedChange: (checked) => table.toggleAllRowsSelected(checked),
}),
cell: ({ row }) =>
renderComponent(Checkbox, {
'aria-label': 'Select Row',
checked: row.getIsSelected(),
disabled: !row.getCanSelect(),
onCheckedChange: (checked) => row.toggleSelected(checked),
}),
enableSorting: false,
enableHiding: false,
} my checkbox component <script lang="ts">
import { Checkbox as CheckboxPrimitive, type WithoutChildrenOrChild } from 'bits-ui'
import Check from 'lucide-svelte/icons/check'
import Minus from 'lucide-svelte/icons/minus'
import { cn } from '$lib/utils.js'
let {
ref = $bindable(null),
class: className,
checked = $bindable(false),
indeterminate = $bindable(false),
...restProps
}: WithoutChildrenOrChild<CheckboxPrimitive.RootProps> = $props()
</script>
<CheckboxPrimitive.Root
class={cn(
'border-primary focus-visible:ring-ring data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground peer box-content size-4 shrink-0 rounded-sm border shadow focus-visible:outline-none focus-visible:ring-1 disabled:cursor-not-allowed disabled:opacity-50 data-[disabled=true]:cursor-not-allowed data-[disabled=true]:opacity-50',
className,
)}
bind:checked
bind:ref
bind:indeterminate
{...restProps}
>
{#snippet children({ checked, indeterminate })}
<span class="flex items-center justify-center text-current">
{#if indeterminate}
<Minus class="size-4" />
{:else}
<Check class={cn('size-4', !checked && 'text-transparent')} />
{/if}
</span>
{/snippet}
</CheckboxPrimitive.Root> |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
I was finally able to solve by looking at the example in column-visibility, Many Thanks for that! what I was missing was the setting rowSelection as $state, and then passing it via getter! let rowSelection = $state<RowSelectionState>({})
function onRowSelectionChange(updater: Updater<RowSelectionState>) {
if (updater instanceof Function) {
rowSelection = updater(rowSelection as RowSelectionState)
} else {
rowSelection = updater
}
}
const table = createTable({
state: {
get rowSelection() {
return rowSelection
},
},
enableRowSelection: true,
onRowSelectionChange,
// ... other props
}) For the checkbox-component, it didn't matter |
Beta Was this translation helpful? Give feedback.
I was finally able to solve by looking at the example in column-visibility, Many Thanks for that!
what I was missing was the setting rowSelection as $state, and then passing it via getter!
For the checkbox-component, it …