React-table: Sort by row properties

Created on 9 Jul 2018  路  2Comments  路  Source: tannerlinsley/react-table

Hello! I can't find, how to sort a table with all row properties?
First i tried defaultSortMethod...

defaultSortMethod = (a, b, desc)

But I need all row data to understand how to sort each of them.
I try to explain i need A & B to be objects with row properties, not only cell value.
Or how to implement the logic other way?
I have some "added" objects, that must be on top of table regardless selected sorting method.

defaultSortMethod = (_a: string, _b: string, desc: boolean): -1 | 0 | 1 => {
const { added } = this.props.history.location.state; // Added objects

const aIsAdded = added ? added.indexOf(_a) > -1 : false;
const bIsAdded = added ? added.indexOf(_b) > -1 : false;

let a = isNil(_a) ? '' : _a;
let b = isNil(_b) ? '' : _b;

a = typeof a === 'string' ? a.toLowerCase() : a;
b = typeof b === 'string' ? b.toLowerCase() : b;

if (!aIsAdded && bIsAdded) {
  return desc ? -1 : 1; // Any way on top
}

if (aIsAdded && !bIsAdded) {
  return desc ? 1 : -1; // Any way on top
}

if (a > b) {
  return 1;
}

if (a < b) {
  return -1;
}

return 0;

}

But this function use flat cell values. So if i sort not ID column (not from added array), this logic stops working.
Hope the question is understandable )

Most helpful comment

I think you may be able to do the following. I don't know if this is the only or best way. I'm just learning to use this component.

For each column:

  • Define a custom accessor function: row => row.
  • Define an id (e.g. the name of the column).
  • Define a custom sortMethod (the values will now be rows, so you can compare, e.g. a.someColName).
  • Define a custom Cell function: row => row.someColName (or whatever).

All 2 comments

I think you may be able to do the following. I don't know if this is the only or best way. I'm just learning to use this component.

For each column:

  • Define a custom accessor function: row => row.
  • Define an id (e.g. the name of the column).
  • Define a custom sortMethod (the values will now be rows, so you can compare, e.g. a.someColName).
  • Define a custom Cell function: row => row.someColName (or whatever).

Thanks a lot, murphyke! Your advice worked perfectly.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

DaveyEdwards picture DaveyEdwards  路  3Comments

Codar97 picture Codar97  路  3Comments

dilipsundarraj1 picture dilipsundarraj1  路  3Comments

mellis481 picture mellis481  路  3Comments

ocalde picture ocalde  路  3Comments