Trentfrompunchbowl1
Trentfrompunchbowl1

Reputation: 109

react table sort not working on calculated column

my "calculated" column Header: 'EV/Resource ($ per oz)' when sorting does not appear to sort in any ascending or descending order when pressed in the react table, it randomize the table sort in a way. Am i doing a "calculated column" correctly ? all my other columns sort correctly.

  {
    Header: 'in-situ ($b)',
    accessor: 'minerals_value',
    Cell: (row) => {
      return (row.value / 100 / 1000000000).toFixed(2)
    },
  },
  {
    Header: 'GMV ($/t)',
    accessor: 'minerals_value_per_ton',
  },
  {
    Header: 'EV/Resource ($ per oz)',
    id: 'evresource',
    accessor: 'evresource',
    sortType: 'basic',

    Cell: (row) => {
      return Number(
        row.row.original.company.enterprise_value /
          100 /
          row.row.original.primary_mineral.contained
      ).toFixed()
    },
  },

table render:

<table {...getTableProps()}>
      <thead>
        {headerGroups.map((headerGroup) => (
          <tr {...headerGroup.getHeaderGroupProps()}>
            {headerGroup.headers.map((column) => (
              <th {...column.getHeaderProps(column.getSortByToggleProps())}>
                {column.render('Header')}
                <span>{column.isSorted ? (column.isSortedDesc ? ' ▼' : ' ▲') : ''}</span>
              </th>
            ))}
          </tr>
        ))}
      </thead>
      <tbody {...getTableBodyProps()}>
        {rows.map((row, i) => {
          prepareRow(row)
          return (
            <tr {...row.getRowProps()}>
              {row.cells.map((cell) => {
                return <td {...cell.getCellProps()}>{cell.render('Cell')}</td>
              })}
            </tr>
          )
        })}
      </tbody>
    </table>

Upvotes: 1

Views: 2159

Answers (1)

Apostolos
Apostolos

Reputation: 10463

You need to implement a custom accessor in order for the sorting to work correctly. Specifically:

  {
    Header: 'EV/Resource ($ per oz)',
    id: 'evresource',
    accessor: customAccessor,

and

function customAccessor(row) {
  return Number(
        row.company.enterprise_value /
          100 /
          row.primary_mineral.contained
      )
  }
}

Upvotes: 1

Related Questions