I want to use server-side sorted Data and want to bypass react-table sorting function. I just want to use Sort click method.
To use a custom sortable function, you can use two different solutions.
You can use directly the defaultSortMethod
props in the ReactTable
component, with here the default method used by the react-table
library that you can replace by your own:
defaultSortMethod: (a, b, desc) => {
// force null and undefined to the bottom
a = a === null || a === undefined ? '' : a
b = b === null || b === undefined ? '' : b
// force any string values to lowercase
a = typeof a === 'string' ? a.toLowerCase() : a
b = typeof b === 'string' ? b.toLowerCase() : b
// Return either 1 or -1 to indicate a sort priority
if (a > b) {
return 1
}
if (a < b) {
return -1
}
// returning 0, undefined or any falsey value will use subsequent sorts or
// the index as a tiebreaker
return 0
},
You can add the props called sortMethod
within a column, where you can call your custom sort function.
Here is an example with a custom sorting by length:
columns={[
{
Header: "Name",
columns: [
{
Header: "First Name (Sorted by Length, A-Z)",
accessor: "firstName",
sortMethod: (a, b) => {
if (a.length === b.length) {
return a > b ? 1 : -1;
}
return a.length > b.length ? 1 : -1;
}
},
{
Header: "Last Name (Sorted in reverse, A-Z)",
id: "lastName",
accessor: d => d.lastName,
sortMethod: (a, b) => {
if (a === b) {
return 0;
}
const aReverse = a.split("").reverse().join("");
const bReverse = b.split("").reverse().join("");
return aReverse > bReverse ? 1 : -1;
}
}
]
}
]
And here is the working example as a whole.