reactjsreact-tabletanstackreact-table-v8

Custom sorting TanStack Table V8


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?


Solution

  • 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;
      }
    }