Lightning datatable does not have a straight forwardan onclick
event where you can identify which row has been clicked. But it can be achieved with a bit of fiddlingBut it can be achieved with a bit of fiddling.
The following worked in playground, but does not work in regular environments.
<lightning-datatable ... onclick={handleClick}></lightning-datatable>
handleClick(event) {
const rowNode = event.toElement.closest('tr');
// Row index (-1 to account for header row)
console.log(rowNode.rowIndex - 1);
// Row Id
console.log(rowNode.dataset.rowKeyValue);
// Use either of these to get the row data from the table data
}
Other Approaches
There are other approaches to this that provides a decent user experience such as using a row button as Rahul Gawale mentions.
Setup your datatable to handle the rowaction
event:
<lightning-datatable ... onrowaction={handleRowAction}></lightning-datatable>
Add a column to the datatable for a button:
{
type: 'button',
typeAttributes: {
label: 'Click me'
}
}
Define a handler for the row action:
handleRowAction(event) {
// contains properties of the clicked row
const row = event.detail.row;
}
Other approaches using datatable include:
- Show the checkboxes and handle
onrowselection
- 1 click - Use an action column with a dropdown of actions - 2 clicks