Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 808
jakiehan Avatar asked Jul 20 '26 06:07

jakiehan


1 Answers

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;
  }
}   
like image 59
Tomas Vancoillie Avatar answered Jul 22 '26 21:07

Tomas Vancoillie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!