Sub topic 9
Adding row actions
This chapter assumes you can build the basic table from earlier chapters: a data array, a columns array, a key-field, and a wired Apex method. You should also be comfortable with LWC event handlers and with async/await.
What a row action is
A row action is a menu item attached to one row. The user clicks the dropdown at the right edge of the row and picks an item such as View or Delete. The table fires one rowaction event. Your handler decides what the item does.
Row actions differ from row selection in two ways:
- An action targets exactly one row, the row whose menu was opened.
- Choosing an action does not select the row or change the current selection.
Use row actions for per-record operations. Use selection when the user picks several rows first and then runs one operation on all of them.
Declaring the action column
An action column is a column definition with type: 'action'. It has no fieldName and usually no label. The menu items go in typeAttributes.rowActions.
const COLUMNS = [
{ label: 'Name', fieldName: 'Name', type: 'text' },
{ label: 'Email', fieldName: 'Email', type: 'email' },
{
type: 'action',
typeAttributes: {
rowActions: [
{ label: 'View', name: 'view', iconName: 'utility:preview' },
{ label: 'Delete', name: 'delete', iconName: 'utility:delete' }
],
menuAlignment: 'auto'
}
}
];Each action object supports these properties:
| Property | Purpose |
|---|---|
| `label` | Text shown in the menu. |
| `name` | Identifier that your handler reads. Treat it as the real key. |
| `iconName` | Optional SLDS icon, for example `utility:delete`. |
| `disabled` | When `true`, the item is visible but cannot be chosen. |
menuAlignment accepts left, right, or auto. auto is the default and lets the table choose a side that stays on screen.
The name value is what your code branches on. The label is display text and may be translated or reworded, so don't branch on it.
Handling the rowaction event
Bind a handler in the template with onrowaction.
<template>
<lightning-card title="Contacts" icon-name="standard:contact">
<lightning-datatable
key-field="Id"
data={data}
columns={columns}
hide-checkbox-column
onrowaction={handleRowAction}>
</lightning-datatable>
</lightning-card>
</template>The event's detail holds two things:
detail.actionis the action object you declared, sodetail.action.nameis the name string.detail.rowis the row object fromdatafor the row that was clicked.
The row object is the same data the table received. Read row.Id from it and don't change its fields. Wired data is read-only, so an assignment such as row.Name = 'x' throws an error in strict mode.
A complete component with View and Delete
This component uses NavigationMixin to open the record page and deleteRecord from Lightning Data Service to delete. It reuses the cacheable getContacts method from the earlier chapters.
import { LightningElement, wire } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';
import { deleteRecord } from 'lightning/uiRecordApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { refreshApex } from '@salesforce/apex';
import getContacts from '@salesforce/apex/ContactController.getContacts';
const COLUMNS = [
{ label: 'Name', fieldName: 'Name', type: 'text' },
{ label: 'Email', fieldName: 'Email', type: 'email' },
{
type: 'action',
typeAttributes: {
rowActions: [
{ label: 'View', name: 'view' },
{ label: 'Delete', name: 'delete' }
]
}
}
];
export default class ContactTable extends NavigationMixin(LightningElement) {
columns = COLUMNS;
data = [];
error;
wiredResult;
@wire(getContacts)
wiredContacts(result) {
this.wiredResult = result;
const { data, error } = result;
if (data) {
this.data = data;
this.error = undefined;
} else if (error) {
this.error = error;
this.data = [];
}
}
handleRowAction(event) {
const actionName = event.detail.action.name;
const row = event.detail.row;
switch (actionName) {
case 'view':
this.viewRecord(row);
break;
case 'delete':
this.deleteRow(row);
break;
default:
}
}
viewRecord(row) {
this[NavigationMixin.Navigate]({
type: 'standard__recordPage',
attributes: {
recordId: row.Id,
objectApiName: 'Contact',
actionName: 'view'
}
});
}
async deleteRow(row) {
try {
await deleteRecord(row.Id);
this.dispatchEvent(
new ShowToastEvent({
title: 'Deleted',
message: `${row.Name} was deleted.`,
variant: 'success'
})
);
await refreshApex(this.wiredResult);
} catch (e) {
this.dispatchEvent(
new ShowToastEvent({
title: 'Delete failed',
message: e.body?.message ?? 'Unknown error',
variant: 'error'
})
);
}
}
}The handler stays short. It reads the action name and hands the row to a method with a clear name. This keeps the switch readable as you add actions.
Why refresh after deleting
getContacts is cacheable, so the wire service can return cached results. After a delete, the cached list still contains the deleted record. refreshApex(this.wiredResult) asks the server for a fresh result and re-runs the wire. That is why the wired function stores the whole result object in wiredResult. refreshApex needs the original wire result, not the unpacked data.
Changing actions per row
A static array shows the same menu on every row. Often the menu should depend on the row. For example, a Contact with no email should not offer a "Send email" item.
Instead of an array, set rowActions to a function with this signature: (row, doneCallback). The table calls the function when the user opens a row's menu. Call doneCallback with the array of actions to show.
function getRowActions(row, doneCallback) {
const actions = [{ label: 'View', name: 'view' }];
if (row.Email) {
actions.push({ label: 'Send email', name: 'email' });
} else {
actions.push({ label: 'No email on file', name: 'noemail', disabled: true });
}
doneCallback(actions);
}
const COLUMNS = [
{ label: 'Name', fieldName: 'Name', type: 'text' },
{ label: 'Email', fieldName: 'Email', type: 'email' },
{ type: 'action', typeAttributes: { rowActions: getRowActions } }
];Three details matter here:
- Define the function at module level, outside the class, so it does not depend on
this. The table calls it without your component as the receiver. doneCallbackcan be called later, after an asynchronous lookup. While you wait, the table shows a loading placeholder in the menu. This makes it possible to check a server value before choosing the actions. Keep that work fast, since the user is waiting with the menu open.- A
disabled: trueitem still appears and tells the user why an operation is unavailable. Omitting the item entirely is better when the operation never applies.
Buttons instead of a menu
If a row needs one obvious operation, a menu hides it behind an extra click. The button and button-icon column types render a button in the cell and also fire rowaction. Their name goes in typeAttributes.
const COLUMNS = [
{ label: 'Name', fieldName: 'Name', type: 'text' },
{
type: 'button-icon',
fixedWidth: 50,
typeAttributes: {
iconName: 'utility:delete',
name: 'delete',
alternativeText: 'Delete',
title: 'Delete'
}
}
];With a button, the action name is read from event.detail.action.name, the same as with a menu. One handler can serve both kinds of column. Prefer the menu when there are three or more actions, and prefer a button when one action dominates.
Common errors
- The menu shows no items.
rowActionsis missing, empty, or a function that never callsdoneCallback. - The handler never runs. The event name is
rowaction, so the attribute isonrowaction. A typo such asonrowactionssilently attaches nothing. action.nameisundefinedor doesn't match. Check the exact string in the column definition. Names are compared with===, so case matters.- The deleted row reappears. The component deleted the record but did not call
refreshApex, or it calledrefreshApexwithdatainstead of the wiredresultobject. - A row action unexpectedly selects rows. It doesn't. If selection changes, another handler is responsible. Check your
onrowselectionlogic. - A dynamic action function throws on
this. Move it out of the class, or capture what it needs in a closure.
Summary of the flow
- Add a column with
type: 'action'and arowActionsarray or function. - Bind
onrowactionon the datatable. - Read
event.detail.action.nameandevent.detail.row. - Run the operation, treating the row as read-only.
- Refresh or replace the data so the table matches the server.
Exercise
A table shows Contacts with a View action for every row and a "Call" action only when the row has a Phone value. Describe how to declare the column, and say what the handler must do to avoid calling a missing number.
Show answer
Use type 'action' with typeAttributes.rowActions set to a module-level function (row, doneCallback). The function builds an array starting with { label: 'View', name: 'view' }, adds { label: 'Call', name: 'call' } only when row.Phone is truthy, and passes the array to doneCallback. In the onrowaction handler, read event.detail.action.name and event.detail.row. For 'call', use row.Phone, and optionally check it again because the data may have changed since the menu was built. Do not modify the row object, since wired data is read-only.
Exercise
After a successful deleteRecord call, the deleted Contact is still in the table. The component calls refreshApex(this.data). What is wrong, and how do you fix it?
Show answer
refreshApex needs the full object that the wire function received, not the unpacked data array. Store the whole result in the wired function (this.wiredResult = result) and call await refreshApex(this.wiredResult) after the delete succeeds.