How to add a button in lightning-datatable in lwc
Just rendering data using lightning-datatable in LWC won’t be sufficient for addressing advanced use cases. When we see data represented as a table, we are confined to the rectangular frame with limited columns as adding more columns makes it look crowded. How about if you can add a button in lightning-datatable in lwc to extend its functionality and improve the overall user experience.
Table of Content
- Why do we need Buttons on lightning-datatable in LWC ?
- Apex Class Code to send the data to lightning-datatable in HTML file
- LWC Code to Show action button on lightning-datatable
- Handling multiple action buttons of lightning-datatable
- Get data of the datatable row for which the button is clicked
- Final Result
Prerequisite
If you are new to lighting-datatable, I would recommend you to read this quick article on Using Lightning Datatable in LWC with Apex
Step 1: Create an Apex Class, Query, and Return Contact records
Create an Apex class with an @AuraEnabled method that will return the List of Contact records.
The method accepts a String parameter called accountId, with this accountId we will query the contact records fields that we want to show in the lightning-datatable.
public with sharing class ContactController {
@AuraEnabled(cacheable=true)
public static List<Contact> getContactRecords(String accountId){
List<Contact> contactList = new List<Contact>();
system.debug('accountId : '+accountId);
try {
if(accountId!=null){
contactList = [Select id,Email,Name,Phone,Owner.Name,Owner.Username from Contact where AccountId=:accountId];
}
system.debug('contactList :'+contactList);
return contactList;
} catch (Exception e) {
throw new AuraHandledException(e.getMessage());
}
}
}
Step 2:Create LWC Component to call the apex class and show contacts in the UI
We are going to create an LWC Component and paste the below HTML code in the .html file.
HTML File
<template>
<lightning-datatable
key-field="id"
data={contactList}
columns={columns}
onrowaction={handleRowAction}
>
</lightning-datatable>
</template>
In the above HTML Code, we have used the lightning-datatable component and onrowaction event handler. We have assigned a javascript method to the onrowaction event handler.
So whenever a column of type action is clicked, the handlerRowAction method will fire in the js code.
JS File
import { LightningElement,wire,api } from 'lwc';
import getContactRecords from '@salesforce/apex/ContactController.getContactRecords';
export default class RelatedAccountContacts extends LightningElement {
actions = [
{ label: 'Show details', name: 'show_details' },
{ label: 'Delete', name: 'delete' }
]
columns = [
{ label: 'Email', fieldName: 'Email', type: 'email' },
{ label: 'Name', fieldName: 'Name', type: 'text' },
{ label: 'OwnerName', fieldName: 'OwnerName', type: 'text' },
{ type: 'action', typeAttributes: { rowActions: this.actions, menuAlignment: 'left' } }
];
@api recordId;
contactList;
@wire(getContactRecords,{accountId:'$recordId'})
contactListRec({data,error}){
if(data){
console.log('data : ',data);
this.contactList = data.map(value=>{
return{...value,OwnerName:value.Owner.Name}
});
}else if(error){
console.log('error',error);
}
}
handleRowAction(event) {
const action = event.detail.action;
const row = event.detail.row;
switch (action.name) {
case 'show_details':
alert('Showing Details: ' + JSON.stringify(row));
break;
case 'delete':
alert('delete row: ' + JSON.stringify(row));
/*
const rows = this.data;
const rowIndex = rows.indexOf(row);
rows.splice(rowIndex, 1);
this.data = rows;
*/
break;
}
}
}
If you have read our article on Using Lightning Datatable in LWC with Apex, you should be well-versed with the above code by now.
There are a couple of modifications we have done to implement onrowaction.
First
We created an array of actionable items that we want to show in the lightning-datatable using an array, which just contains on object key-value pair of label (shows in ui) and name (don’t show in ui, used for reference in js code).
actions = [
{ label: 'Show details', name: 'show_details' },
{ label: 'Delete', name: 'delete' }
]
Second
In our columns array, we have created a new value (JSON Object) of type action with typeAttribute where we are customizing its behavior, by assigning the actions array(created above) to its rowActions attribute.
columns = [
...rest of the column values here....
{ type: 'action', typeAttributes: { rowActions: this.actions, menuAlignment: 'left' } }
];
Note: typeAttributes provide custom formatting capabilities for different data types. Different datatype have different typeAttributes For example a data type url has label, target and tooltip typeAttributes, we assign values to these attributes to customize the behavior as per our requirement.
Third
We then create a method called handleRowAction and write the functionality to handle the click/onrowaction event.
handleRowAction(event) {
const action = event.detail.action;
const row = event.detail.row;
switch (action.name) {
case 'show_details':
alert('Showing Details: ' + JSON.stringify(row));
break;
case 'delete':
alert('delete row: ' + JSON.stringify(row));
break;
}
}
In our handleRowAction method, we can get a reference to the row we clicked using event.detail.row and the action which triggered the event using event.detail.action
How do we know which action triggered the handleRowAction method?
Now, remember we defined two actions in our actions array Show Details and Delete, we can use event.detail.action.name to get the name of the action and then with a switch case statement, we can execute a specific code block for each action as we want.
How to get the value of the row I clicked the action on?
We can use event.detail.row.Email to fetch the value in the email column, replace the <columnName> in event.detail.row.<columnName> to get the value of any column present in the column array.
The <columnName> should match the name mentioned in the columns array fieldName attribute mentioned in the JS File Code above.

Note: All actions defined on our datatable have only on handler, the way to identify which action button/icon triggered the event is by checking action’s name attribute (see actions array created above) using event.detail.action.name.
Once you get the above piece of code running, you can replace the alert code inside the switch case statement to implement a range of functionalities like:
- Opening a Modal window in Lightning Web Component
- Opening a new tab in the browser using Lightning Web Component.
- or, call ChatGPT API to auto-generate your Cover Letter
There are endless possibilities of what you can do. Use your creativity and mention in the comment section below any interesting feature that you can implement using what you have learned today.
Time for the Final Result
In the below screenshot, you see two actions that are created. Observe how the label attribute is used to show entered value in the UI. On click of any of the two actions, the handleRowAction method is called in the js file.

Conclusion: Why do we need to add a button in lightning-datatable in lwc ?
One of the best ways to address the above issue is to implement a drill down feature and add a button in lighting-datatable in LWC. With onrowaction with lighting-datatable we can perform certain actions like:
- Navigate to different page to show more details about the row value clicked. In the Salesforce layout these are lookup values, which take us to the details page.
- Show a Modal window to capture some details and make a callout or save the value in Salesforce. Example: Creating a case for a record listed in the lightning-datatable without navigating to a new page, by just using a Modal window.
- On click of an Icon in lighting-datatable peform async action in the background. Example: Delete the record by clicking on the delete icon, mark a record as inactive by clicking on the exclamation icon.
To address these use cases, we are going to use onrowaction with lightning-datatable in LWC. Using onrowaction, we can assign a javascript function that will be called when there is a click event on columns that are of data type action.
Note: Find the complete list of lightning-datatable column data types here. In our example we are using actions datatype for some columns and its attribute rowActions.