Make react-table sort only between ascending and descending order?

4.9k views Asked by At

React table sorting has 3 conditions, default view, ascending and descending as shown in their official sample https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/sorting

Now, I want to make it only between ascending and descending and remove default view. I've tried to sort the first column by default

 useTable(
    {
      columns,
      data,
      initialState: {
        pageIndex: 0,
        pageSize: 10,
        sortBy: [
          {
            id: "asset",
            desc: false,
          },
        ],
      },
    },
  )

but default view is still there when I click the column and I don't know how to remove it. I can't find it in their documentation either.

3

There are 3 answers

0
Cjtoday On BEST ANSWER

The useSortBy documentation mentions a disableSortRemove option that can be specified when calling useTable.

If true, the un-sorted state will not be available to columns once they have been sorted.

0
Cat Perry On

For anyone coming to this React Table sorting question later, here's a bit more specificity. If you use disableSortRemove: true alone you'll still have the very first click be an "unsorted" state, and then subsequent clicks are sorted asc or desc. That's perhaps not the UI you want, as a button click, first or not, should do something, but with that one variable, on first click it wont.

So that you dont have to click the sort button twice to see sorting, do this!

const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow } = useTable(
    {
      columns: tableColumns,
      data: tableData,
      disableSortRemove: true,
      defaultCanSort: true,
      initialState: {
        sortBy: [{ id: tableData[0]?.totalSeries?.totalSeries, desc: true }], //TODO: adjust TableData type file
      },
    },
    useSortBy
  );

Here we've added 3 things rather than just the one disableSortRemove: true. We've added:

disableSortRemove: true, defaultCanSort: true, and initialState: { sortBy: [{ id: tableData[0]?.totalSeries?.totalSeries, desc: true }] // IMPORTANT: use your own data shape here },

I don't think you need the second one (defaultCanSort: true) BUT the first and third give you the effect you want: On page load, sorting is on and once you click the sort button it sorts the opposite way.

Done. Sorted.

0
Avani Joshi On

enableSortingRemoval:false,

Enables/Disables the ability to remove sorting for the table. If true then changing sort order will circle like: 'none' -> 'desc' -> 'asc' -> 'none' -> ...

If false then changing sort order will circle like: 'none' -> 'desc' -> 'asc' -> 'desc' -> 'asc' -> ...

Please find this property 'enableSortingRemoval' here- https://tanstack.com/table/v8/docs/api/features/sorting