Anarno
Anarno

Reputation: 1640

react-table row selection with custom field instead of index

I'm using the react-table package. I made a simple table with row selection. The problem is: The row selection result is an object with indexes:

{
 0: true,
 1: true,
 ...
}

But I want to be the primary key of my data like this:

{
  EXoxMjyd4leYABdpuy8m: true,
  2gXlClA38AU8sSM5jnZ7: true,
  ...
}

Code example

In the documentation, I can't find a configuration where I can set the selection key. The question is, how can I achieve the second example?

Upvotes: 5

Views: 9777

Answers (2)

ipikuka
ipikuka

Reputation: 824

If you are using version 8 react-table; you can use instance.getSelectedRowModel() in order to get the original (data model of the rows) of the selected rows as well as the row indexes.

For instance:

const arraySelectedUsersId = instance.getSelectedRowModel().rows.map(({ original }) => (original as User).id)

Upvotes: 2

Fiodorov Andrei
Fiodorov Andrei

Reputation: 2028

You need to overwrite the table option getRowId.

Example:

const getRowId = (row, relativeIndex, parent) => {
   // In row object you have access to data. 
   // You can choose parameter. In this example I used uniqueId
   return parent ? [parent.id, row.uniqueId].join('.') : row.uniqueId;
}

Here is live example:

Edit tannerlinsley/react-table: row-selection-controlled (forked)

Upvotes: 9

Related Questions