react-tablereact-table-v7

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


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?


Solution

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