How does one supply a custom sort function for react table 7?

Viewed 17060

The documention for useSortBy sortType properties says:

sortType: String | Function(rowA: <Row>, rowB: <Row>, columnId: String, desc: Bool)

    Used to compare 2 rows of data and order them correctly.
    If a function is passed, it must be memoized. The sortType function should return -1 if rowA is larger, and 1 if rowB is larger. react-table will take care of the rest.
    String options: basic, datetime, alphanumeric. Defaults to alphanumeric.
    The resolved function from the this string/function will be used to sort the this column's data.
        If a string is passed, the function with that name located on either the custom sortTypes option or the built-in sorting types object will be used.
        If a function is passed, it will be used.
    For more information on sort types, see Sorting

but doesn't explain fully how to use it.

So how does one supply a sortType function?

5 Answers

The arguments for the sortType function are: (rowA, rowB, columnId, desc)

columnId identifies which column the row is being sorted by, and so allows getting the cell value.

desc identifies the direction of the sort. Even though desc is supplied, the sort function should NOT reverse the return values. react table automatically does this.

For example:

sortType: React.useMemo((rowA, rowB, id, desc) => {
       if (rowA.values[id] > rowB.values[id]) return 1; 
       if (rowB.values[id] > rowA.values[id]) return -1;
        return 0;
})

example of where to use sortType:

const columns = [{       
        Header: ...
        accessor: ...
        sortType: /*sortType func goes here... */        
}, ...]

function MyTable(columns, data)
{
 const { /*...*/ } = useTable({columns,data})
}

Per your doc citation, sortType is a Column option.

The following options are supported on any Column object passed to the columns options in useTable()

For instance, modify the Quick Start's Define Columns, like so:

const columns = React.useMemo(
  () => [
    {
      Header: 'Column 1',
      accessor: 'col1', // accessor is the "key" in the data
    },
    {
      Header: 'Column 2',
      accessor: 'col2',
      sortType: compareNumericString // custom function
    },
  ],
  []
)

function compareNumericString(rowA, rowB, id, desc) {
    let a = Number.parseFloat(rowA.values[id]);
    let b = Number.parseFloat(rowB.values[id]);
    if (Number.isNaN(a)) {  // Blanks and non-numeric strings to bottom
        a = desc ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY;
    }
    if (Number.isNaN(b)) {
        b = desc ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY;
    }
    if (a > b) return 1; 
    if (a < b) return -1;
    return 0;
}

I had quite a bit of trouble figuring this one out as well. Here's how I did it. It's in typescript, but if you need it in plain js, just remove all the typings. 1st, here' the custom sort. It will sort strings, and always put the nulls/blanks/undefined at the end.

const customStringSort: any = (rowA: Row, rowB: Row, columnId: string, desc: boolean) => {
  const defaultVal = desc ? 'AAAAAAAAAAAA' : 'ZZZZZZZZ';
  return (rowA.values[columnId] ?? defaultVal)
    .localeCompare(rowB.values[columnId] ?? defaultVal);
};

There are 2 things to notice about this.

  1. I couldn't figure out why typescript didn't like it when the return was defined as a number. I hate to use any, but this works.
  2. The react table documentation indicates that this must be memoized. This is not, but it works still.

Next you have to add this function to the sortTypes.

const sortTypes: Record<string, SortByFn<SomeObject>> = {
  customStringSort: customStringSort,
};

Next, add the sortTypes to the useTable instance.

const {
  getTableProps,
  getTableBodyProps
  headerGroups,
  rows,
  prepareRow,
  } = useTable(
    {
      columns,
      data,
      sortTypes
    },
  useSortBy
);

Now you can add the custom function into your column definitions.

const columns: Column<SomeObject>[] = React.useMemo(() => 
  [
    { accessor: 'someColumnID', Header: 'Some Column', sortType:'customStringSort' },
  ],
  [],
);

Hope this helps!

--Edit: If you want to memoized the function, this works. Just replace customStringSort with customStringSortMemo where appropriate.

const customStringSort: any = React.useCallback((rowA: Row, rowB: Row, columnId: string, desc: boolean) => 
  {
  const defaultVal = desc ? 'AAAAAAAAAAAA' : 'ZZZZZZZZ';
  return (rowA.values[columnId] ?? defaultVal).localeCompare(rowB.values[columnId] ?? defaultVal);
  },
[]);
    
const customStringSortMemo = React.useMemo(() => customStringSort[customStringSort]);

Custom Sort ini Last Header in const columns

const columns = React.useMemo(
            () => [
              {
                Header: 'ID',
                accessor: 'IDXX_GRPX'
              },
              {
                Header: 'Nama Group',
                accessor: 'NAMA_GRPX'
              },
              {
                Header: 'Kecamatan',
                accessor: 'KECX_DESC'
              },
              {
                Header: 'Kelurahan',
                accessor: 'AREA_DESC'
              },
              {
                Header: 'Unit',
                accessor: 'BUSS_CODE'
              },
              {
                Header: 'Kode Urut',
                accessor: 'KODE_URUT',
                sortType: (a, b) => {
                      if (a.values['KODE_URUT'] < b.values['KODE_URUT']) {
                          return -1;
                      } else if (a.values['KODE_URUT'] > b.values['KODE_URUT']) {
                          return 1;
                      };
    
                      return 0;
                  }
              }
            ],
            []
          );
Related