[SalesForce] Lightning Web Component: Can we catch rowclick event lightning-datatable just click

I want to make lightning-datatable with row-click event.
It's without checkbox or onrowaction pulldown or link like below.

enter image description here

I'm looking for lightning-table events, but almost article uses onrowaction.
Is there way to row-click on lightning-datatable?

When I wrote onclick event on lightning-datatable, it looks that can't get row value.

Now, I make code like this

list.html

   <template if:true={searchedResult} data-item={searchedResult.id}>
            <lightning-datatable
                key-field="id"
                data={searchedResult} hide-checkbox-column
                columns={columns} onclick={handleRowAction}>
            </lightning-datatable>
        </template>

list.js

columns = [
    {label: 'Name', fieldName:'name', type: 'text'},
    {label: 'AccountName', fieldName:'note', type: 'text'},
    {label: 'LastUpdate', fieldName:'lastUpDate', type: 'date'}, 
];
    handleRowAction(e) {
        console.log(e);
        publish(this.sfidContext, SFIDChannel, e);
    }

Best Answer

Lightning datatable does not have an onclick event where you can identify which row has been clicked. But 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