rowreact-tabletanstack

@tanstack/react-table v8: How to get next row when sorted


I have a sorted(!) @tanstack-table v8 (aka react-table).

In each tr there is an onClick-Handler which gives me access to the current row-object.

So far so good.

But how do I get access to the next (or previous) row?

Sadly row.index isn't working as it doesn't reflect the sorting. There's no "sortedIndex" as far as I can see?


Solution

  • After some digging I found Table.getSortedRowModel(), which returns the sorted row model!

    Link to the docs: https://tanstack.com/table/v8/docs/api/features/sorting#getsortedrowmodel

    I use the following to get the row-index of a row containing mySearchValue in a specific column of the table:

    let currentIndex = table
        .getSortedRowModel()
        .rows.findIndex((row) => row.getValue("<ColumnKey>") == mySearchValue);
    

    Using this its quite easy to get a value in a column of the i.e. previous row

    let prevRowFieldValue = table.getSortedRowModel()
        .rows[currentIndex - 1].getValue("<ColumnKey>");
    

    For me this works perfectly, maybe it helps someone!