2

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);
    }
3
  • Did you try to add a button/button-icon in the cell? Commented Sep 10, 2020 at 9:08
  • Thank you your response rahul. I don't try add a button yet. It means button works with row click? or show button in every row?
    – Asae
    Commented Sep 10, 2020 at 9:18
  • yes if you column type as button or icon button it will be displayed on each row and you can get the clicked row in the event detail. Commented Sep 10, 2020 at 10:56

3 Answers 3

4

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
1
  • Thank you akiradev. I tried event.toElement.closest, but it doesn't work. So I'll use you & rahul's idea adding button in every row. When I have enough time, I'll make original table which can rowclick.
    – Asae
    Commented Sep 11, 2020 at 4:17
5

I was able to get the row-click working by extending Lightning-Datatable and manually assigning a click handler in a lifecycle method. Wrote a blog post with a more detailed example for my use case.

Example:


export default class DatatablePlus extends LightningElement {
...

  renderedCallback() {
    // Prevent multiple handler assigment
    if (this._hasRendered) {
        return;
    }

    const table = this.template.querySelector('tbody');
    table.addEventListener(
        'click',
        (e) => { console.log(e.target.tagName + ' was clicked.'); }
    );
        
    this._hasRendered = true;
  }

}

A couple things to note:

a) With this pattern we don't have access to a detail prop, and target could vary. As such, you might want to normalize the clicked target by e.g. finding the TR element which has an "id" value attached as an attribute.

b) If you want to send the clicked Row's Id to a parent component; Custom events won't work since they get re-targeted when crossing the Shadow barrier. There are a few patterns that Salesforce recommends. However, I found that a window.postMessage served my needs.

3
  • This is quite useful ! However on using this, my table's column headers were had a problem. The dividers for each column were out of their place. Did you also make any adjustments to the CSS ?
    – N_H1922
    Commented Jan 12, 2022 at 10:26
  • I don't recall any special adjustments for column styling that were due to this method. Did the column configuration api for lightning-datatable not work? developer.salesforce.com/docs/component-library/bundle/… (section: Working with Column Properties ) Commented Jan 13, 2022 at 17:08
  • Yes I did try the column related settings but I couldn't make it work. The width of the columns wasn't working. Even if you clicked on the dividers and tried to extend the width, it wouldn't change in the table header.
    – N_H1922
    Commented Jan 15, 2022 at 16:09
1

H you can use the following logic

  1. add click listener <lightning-datatable ... onclick={handleClick}></lightning-datatable>

  2. use currentTarget and access data itself

     handleClick(event){
     const data = event.currentTarget.data;
    } 
    

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .