Reputation: 57
I am trying to apply the sorting method to one of the columns in my table. That column is having numerical values and empty values ("--"). I would like to sort the values in ascending and descending manner. And I want all the empty values should go to the bottom of the table in both sorting types.
Could anyone please suggest a custom sorting function to use with react-table-6?
Thank You...
Upvotes: 2
Views: 2264
Reputation: 14622
You can override the sortMethod
column property, by providing a custom sorting function here. It uses a standard comparator function, taking in two values and returning -1, 0 or 1 to indicate relative order.
See the example here: https://codesandbox.io/s/github/tannerlinsley/react-table/tree/v6/examples/custom-sorting?file=/src/index.js:675-685
A short code snippet for how to use it:
render() {
const { data } = this.state;
return (
<div>
<ReactTable
data={data}
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;
}
},
Upvotes: 0
Reputation: 549
It's crazy that you asked this because I just finished working on this exact problem with the exact same requirements -- lucky you!
This is in TypeScript, but you can remove the types if you want.
The columns:
const columns: Column[] = useMemo(
() => [
{
Header: 'Rank',
accessor: 'rank',
sortType: rankSort, // This is the rankSort() function below
maxWidth: 10,
},
...
],
[]
);
This is the ranking function:
const getRankValueString = (value: number, desc?: boolean): string => {
let stringValue = value.toString();
if (stringValue === '--') {
if (desc) {
stringValue = '-9999999';
} else {
stringValue = '9999999';
}
return stringValue;
}
for (let i = stringValue.length; i < 6; i++) {
stringValue = `0${stringValue}`;
}
return stringValue;
};
const rankSort = (
rowA: Row,
rowB: Row,
columnId: string,
desc?: boolean
): number => {
return getRankValueString(rowA.values[columnId], desc).localeCompare(
getRankValueString(rowB.values[columnId], desc)
);
};
It's a bit hacky, but it sorts values up to 6 digits. I'm open to optimizations.
Upvotes: 1