Reputation: 575
By default, react table sorting is case sensitive.
In order to make it insensitive we have to write a custom sort function.
I like this answer from https://github.com/react-tools/react-table/issues/335.
This would help.
Upvotes: 5
Views: 11132
Reputation: 326
(firstRow, secondRow, accessor) => {
// get from lodash
const firstValue = get(firstRow.values, accessor, '');
const secondValue = get(secondRow.values, accessor, '');
return firstValue > secondValue ? 1 : -1;
}
Above is the solution I used to assign to "alphanumeric", which covered both cases. Because, as in many programming languages, strings are compared lexicographically hence we need not change the case. And even comparing with numbers works fine.
Upvotes: 0
Reputation: 469
The proper way to sort a column with react-table and with a case-insensitive approach, would be to use sortType
on a column and then provide a custom function.
/**
*
* React Table helper to sort tables
* with case-insensitive support
*
*/
export const customInsensitiveCompare = (
rowA: Row,
rowB: Row,
columnId: string,
desc: boolean
) => {
const valueA = rowA.values[columnId].toLowerCase();
const valueB = rowB.values[columnId].toLowerCase();
if (desc) {
return valueA.localeCompare(valueB) > 0 ? 1 : -1;
}
return valueB.localeCompare(valueA) > 0 ? -1 : 1;
};
If you do not use Typescript just remove the types and everything will work fine. Take care that we need to return only -1
or 1
and localeCompare sometimes can return 0
or even different values according to MDN docs, that why we assign only -1
, 1
as react-table expects.
Upvotes: 0
Reputation: 71
For case insensitive and numbers sorting pass sortTypes
in table props like this:
useTable({
sortTypes: {
alphanumeric: (row1, row2, columnName) => {
const rowOneColumn = row1.values[columnName];
const rowTwoColumn = row2.values[columnName];
if (isNaN(rowOneColumn)) {
return rowOneColumn.toUpperCase() >
rowTwoColumn.toUpperCase()
? 1
: -1;
}
return Number(rowOneColumn) > Number(rowTwoColumn) ? 1 : -1;
}
}
})
Upvotes: 7
Reputation: 10270
The question mentions sorting but links to filtering. For custom sorting the app's owner mentions on Github
to pass a sortTypes: { alphanumeric: MyCustomFunc }
in the table props, like this:
useTable({
columns,
sortTypes: {
alphanumeric: (row1, row2, columnName) => {
return compareIgnoreCase(
row1.values[columnName],
row2.values[columnName]
)
},
},
},
useSortBy
)
Upvotes: 4
Reputation: 575
//function to sort the results
function filterCaseInsensitive(filter, row) {
const id = filter.pivotId || filter.id;
return (
row[id] !== undefined ?
String(row[id].toLowerCase()).startsWith(filter.value.toLowerCase())
:
true
);
}
// react table code goes here
<ReactTable
data={data}
columns={columns}
filterable
defaultFilterMethod={(filter, row) => filterCaseInsensitive(filter, row) }
/>
Upvotes: 6