How to get the row index of a clicked cell in react-table?
16,071
Solution 1
Straight from the React-table docs:
// When any Td element is clicked, we'll log out some information
<ReactTable
getTdProps={(state, rowInfo, column, instance) => {
return {
onClick: (e, handleOriginal) => {
console.log("A Td Element was clicked!");
console.log("It was in this row:", rowInfo);
// IMPORTANT! React-Table uses onClick internally to trigger
// events like expanding SubComponents and pivots.
// By default a custom 'onClick' handler will override this functionality.
// If you want to fire the original onClick handler, call the
// 'handleOriginal' function.
if (handleOriginal) {
handleOriginal();
}
}
};
}}
/>
The rowInfo
object will be of this shape:
row: Object, // the materialized row of data
original: , // the original row of data
index: '', // the index of the row in the original array
viewIndex: '', // the index of the row relative to the current view
level: '', // the nesting level of this row
nestingPath: '', // the nesting path of this row
aggregated: '', // true if this row's values were aggregated
groupedByPivot: '', // true if this row was produced by a pivot
subRows: '', // any sub rows defined by the `subRowKey` prop
By accessing rowInfo.index
you will get the row index of the cell.
Working example: https://codesandbox.io/s/nr8w9q6z2m
Solution 2
If you are doing a functional rendering this can be help
<tbody {...getTableBodyProps()}>
rows.slice(0, 10).map((row, i) => {
prepareRow(row);
return (
<tr {...row.getRowProps()}>
{row.cells.map((cell, i) => {
return (
<td {...row.getRowProps({onClick: (e)=>handleTableCellClick(e,row)})}>{cell.render("Cell")}</td>
);
})}
</tr>
);
})
</tbody>
Author by
tommy123
Updated on June 28, 2022Comments
-
tommy123 about 2 years
Hello I am working with React Table. Here is my Demo Sandbox - https://codesandbox.io/embed/vq60okkz20?codemirror=1
I want to get the row index of the clicked cells div. I have two columns where the cells have a clickable div. I want to get the row index for these cells
-
Alejandro over 5 yearsPossible duplicate of Select row on click react-table
-
-
Alejandro over 5 yearsprobaly
getTrProps
is more suitable -
Murli Prajapati over 5 years@tommy123 updated the answer with the working example.