Step 6: Add Sorting
Sorting is enabled by default at the table level. You just need to enable it on the columns you want to be sortable:
// columns.ts — updated
export const columns = [
columnHelper.accessor('name', {
header: 'Name',
enableSorting: true,
}),
columnHelper.accessor('department', {
header: 'Department',
enableSorting: true,
}),
columnHelper.accessor('salary', {
header: 'Salary',
enableSorting: true,
cell: ({ getValue }) => `$${getValue().toLocaleString()}`,
}),
columnHelper.accessor('startDate', {
header: 'Start Date',
enableSorting: true,
sortingFn: 'datetime',
}),
columnHelper.accessor('active', {
header: 'Active',
cell: ({ getValue }) => (getValue() ? 'Yes' : 'No'),
}),
]
Click a column header to sort ascending, click again for descending, and a third time to remove the sort. Hold Shift and click another column for multi-column sorting.
Controlled Sorting (Optional)
If you need to know the current sort state or set it programmatically:
import { useState } from 'react'
import type { SortingState } from '@zvndev/yable-react'
export function EmployeeTable() {
const [sorting, setSorting] = useState<SortingState>([])
const table = useTable({
data: employees,
columns,
state: { sorting },
onSortingChange: setSorting,
})
return <Table table={table} />
}