'Is there a way to make React Carbon DataTable entries selectable and clickable at the same time?
So, I am using the React Carbon component library, and I am using its DataTable component.
So, when a row is clicked, it redirects to a different page showing details about that entry, and this is done with the onClick prop. However, when this happens, clicking the checkboxes does not work, as the click event instead goes to the onClick. On the other hand, when I comment out the onClick prop, then the checkboxes work as they should. Therefore, I wanted to know how I could get both of these to work simultaneously. (Maybe something like making the onClick not apply to the cell containing the checkbox, but I am not sure how to do that)
Here is the code for the DataTable component:
<DataTable rows={filteredData} headers={headers} isSortable>
{({
rows,
selectedRows,
headers,
getTableProps,
getHeaderProps,
getRowProps,
getSelectionProps,
}) => (
<Table {...getTableProps()}>
<TableHead>
<TableRow>
{selectedRecords && (<TableHeader />)}
{headers.map((header) => (
<TableHeader {...getHeaderProps({ header })}>
{header.header}
</TableHeader>
))}
{overflowMenuItems && (
<TableHeader></TableHeader>
)}
</TableRow>
</TableHead>
<TableBody>
{rows.map((row, index) => (
index >= rowRange[0] && index <= rowRange[1] && (
<TableRow
key={index}
{...getRowProps({ row })}
// HERE IS THE ONCLICK EVENT
onClick={(e) => handleRowClick(row.id, index)}
>
{selectedRecords && (
<TableSelectRow
{...getSelectionProps({ row })}
onSelect={e => {
getSelectionProps({row}).onSelect(e);
let selected = selectedRecords;
// If currentRow already in selectedRows (deselect)
if(selected.find((r, i) => {
return r === row.id
})) {
selected.splice(selected.findIndex(r => r === row.id), 1)
}
// New Entry
else
selected.push(row.id);
setSelectedRecords(selected);
}}
checked={selectedRecords.includes(row.id)}
/>
)}
{row.cells.map((cell) => (
<TableCell key={cell.id}>{cell.value}</TableCell>
))}
{overflowMenuItems && (
<td>
<OverflowMenu size={'sm'} flipped>
{overflowMenuItems.map(itemProps => {
return (
<OverflowMenuItem
{...itemProps}
onClick={itemProps.onClick(row.id)}
/>
)
})}
</OverflowMenu>
</td>
)}
</TableRow>
)
))}
</TableBody>
</Table>
)}
</DataTable>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

