Custom sorting TanStack Table V8
Asked Answered
J

2

7

How can I sort a column if there is two values in the cells?

columnHelper.accessor('violations', {
  id: 'violations',
  header: () => <p>Violations</p>,
  cell: (info) => (
    <div>
      <p>{info.getValue().count}</p>
      <p>{info.getValue().percent}%</p>
    </div>
  ),
}),

If there is a way, could you provide an example of an implementation?

Justness answered 11/3, 2023 at 21:48 Comment(1)
you can use sortingFns and create a custom sorting function for violations column. Sorting Fns Docs.Trottier
H
13

You can pass a custom sorting function per column. This is an example sorting on count:

{
  id: 'violations',
  header: () => <p>Violations</p>,
  cell: (info) => (
    <div>
      <p>{info.getValue().count}</p>
      <p>{info.getValue().percent}%</p>
    </div>
  ),
  sortingFn: (
    rowA,
    rowB,
    columnId
  ) => {
    const numA = rowA.getValue(columnId).count;
    const numB= rowB.getValue(columnId).count;

    return numA < numB ? 1 : numA > numB ? -1 : 0;
  }
}   
Historic answered 14/3, 2023 at 8:39 Comment(2)
Thanks, I did it this wayJustness
How do you trigger the custom sorting function on click? column.toggleSorting(column.getIsSorted() === "asc") isn't working for meBible
F
0

It is also accessible with external functions, as demonstrated in the following example:

declare module '@tanstack/table-core' {
  interface SortingFns {
    myCustomSorting: SortingFn<unknown>
  }
}

const columns = [
  columnHelper.accessor('violations', {
     header: () => <p>Violations</p>,
     cell: (info) => (
        <div>
          <p>{info.getValue().count}</p>
          <p>{info.getValue().percent}%</p>
         </div>
      ),
      sortingFn: 'myCustomSorting'
  })
]

const table = useReactTable({
  data,
  columns,
  sortingFns: {
    myCustomSorting: myCustomSorting
  },
})

function myCustomSorting(rowA: any, rowB: any, columnId: any): number {
  return rowA.getValue(columnId).value < rowB.getValue(columnId).value ? 1 : -1,
}
Filemon answered 23/10, 2023 at 12:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.