react-bootstrap-table icon indicating copy to clipboard operation
react-bootstrap-table copied to clipboard

Sorting doesn't work on the columns bound to nested json data

Open JyotiRani opened this issue 8 years ago • 5 comments

I have following sample JSON: {"product": "p1", "type": 1, "typeDetails": {"id": 1, "type:": "sample"}, } which is mapped to the bootstrap table with sorting enabled.

TableHeaderColumn dataField='typeDetails' width="25%" dataSort dataFormat={showProductType}>Product Type</TableHeaderColumn

function showCompanyType(cell, row) { return cell.type; }

Table renders well, but sorting doesn't work on the type column, please suggest how to get sorting work on this column?

JyotiRani avatar Dec 05 '17 10:12 JyotiRani

Neither search works. Actually, I'm looking for solutions in both situations.

libasoles avatar Dec 07 '17 15:12 libasoles

There are two ways to fix this:

1. Don't use nested json, flatten the data before passing it to the table. eg:

const data = [
  {
    product: 'p1',
    type: 1,
    typeDetails: {
      id: 1,
      type: 'sample'
    }
  },
  ...
];

const flattenData = data.map((row) = {
  return {
    product: row.product,
    type: row.type,
    typeDetails: row.typeDetails.type
  };
});

2. Provide your own sort function:

function detailsSort(a, b, sortOrder) {
  if (sortOrder === 'desc') {
    return a.type > b.type ? -1 : 1;
  } else {
    return a.type > b.type ? 1 : -1; 
  }
}

<TableHeaderColumn
  dataField="typeDetails"
  width="25%"
  dataSort
  dataFormat={showProductType}
  sortFunc={detailsSort}
>
  Product Type
</TableHeaderColumn>

VictorChen avatar Dec 07 '17 20:12 VictorChen

Thanks @VictorChen, i opted for option#2 and it worked for me, but search also doesn't work for these nested fields. Do we have any hooks for search also?

JyotiRani avatar Dec 08 '17 07:12 JyotiRani

@JyotiRani take a look at this for search: https://github.com/AllenFang/react-bootstrap-table/issues/1788

It doesn't work for me anyway (because the method is just being called for a few cols). But it's supposed to.

libasoles avatar Dec 08 '17 13:12 libasoles

thanks @libasoles it worked for me!

JyotiRani avatar Dec 11 '17 07:12 JyotiRani