react-table not sorting decimal numbers correctly

Viewed 541

I'm trying to sort a column with a decimal using react-table, but the sorting is rendering incorrectly.

This is what the order renders when trying to sort the age column from top to bottom:

0.89        
0.14    
0.8

When it should render this:

0.89
0.8 
0.14    

Demo of issues using codesandbox: https://codesandbox.io/s/new-bird-puhhr?file=/src/App.js

Click the age column to re-produce the issue.

I've managed to get it working by overriding the orderByFn. But this hack will only work for sorting one column.

orderByFn: function defaultOrderByFn(arr, funcs, dirs) {
  if (dirs[0]) {
    return arr.sort((a, b) => b.original.age - a.original.age);
  } else {
    return arr.sort((a, b) => a.original.age - b.original.age);
  }

Any help working this issue out is much appreciated.

1 Answers

You can apply your own sorting logic per column in react-table.

As I see on your example you were close to solve the issue by using the sortType field to override the default sorting when initializing your columns.

Apply this arrow function in the sortType field of the age column, and sorting should work fine in both ascending and descending since the library will take care of it.

sortType: (rowA, rowB) => {
          if (rowA.original.age > rowB.original.age) return -1;
          if (rowB.original.age > rowA.original.age) return 1;
        }

See codesandbox based on your example.

Related