Sub topic 10
Displaying data with lightning-datatable
This chapter covers lightning-datatable, the base component that renders rows and columns of records. It assumes you can read a Lightning web component (HTML template, JavaScript class, CSS file), know how lightning-card and lightning-input work, and can handle events with onclick-style handlers. You need a Salesforce org or scratch org to run the examples.
By the end you will be able to define columns, supply rows, handle row actions, sorting and selection events, and avoid the usual mistakes.
What the datatable does
lightning-datatable is a base component that shows tabular data. It takes two required inputs: a list of column definitions and a list of row objects. It handles formatting, column headers, row selection, sorting indicators, inline editing, and keyboard navigation. It applies SLDS styling itself, so you do not add table classes.
The component does not fetch data, sort data, or save edits. Your component owns the data. The datatable reports user actions through events, and your code decides what to do with them.
The minimum working table
The template needs key-field, data, and columns.
<template>
<lightning-datatable
key-field="id"
data={contacts}
columns={columns}
hide-checkbox-column
></lightning-datatable>
</template>The controller defines the columns and rows.
import { LightningElement } from 'lwc';
export default class ContactTable extends LightningElement {
columns = [
{ label: 'Name', fieldName: 'name', type: 'text' },
{ label: 'Phone', fieldName: 'phone', type: 'phone' },
{ label: 'Email', fieldName: 'email', type: 'email' }
];
contacts = [
{ id: '1', name: 'Ada Lovelace', phone: '5551230001',.com' },
{ id: '2', name: 'Grace Hopper', phone: '5551230002', email: '[email protected]' }
];
}key-fieldnames the property that uniquely identifies each row. Here it isid. The datatable uses it to track rows across updates and selections. If values repeat, selection and rendering behave incorrectly.datais an array of plain objects. Each object is one row.columnsis an array of column definitions. EachfieldNamepoints to a property of the row objects.
hide-checkbox-column removes the selection checkboxes. Leave it off when users need to select rows.
Column definitions
Each column object accepts these common properties.
| Property | Purpose |
|---|---|
| `label` | Header text. Required. |
| `fieldName` | Property of the row object to display. Required for data columns. |
| `type` | How the value is formatted. Defaults to `text`. |
| `sortable` | Shows a sort control in the header when `true`. |
| `initialWidth` | Starting width in pixels. |
| `typeAttributes` | Settings specific to the column type. |
| `cellAttributes` | Settings for the cell, such as alignment or an icon. |
| `editable` | Allows inline editing when `true`. |
Built-in types include text, number, currency, percent, date, boolean, email, phone, url, location, button, button-icon, and action. The type controls formatting only. A currency column still needs a number in the data, not a string such as "$5.00".
typeAttributes and cellAttributes configure the type. A currency column with a currency code looks like this:
columns = [
{ label: 'Name', fieldName: 'name', type: 'text', sortable: true },
{
label: 'Annual revenue',
fieldName: 'revenue',
type: 'currency',
typeAttributes: { currencyCode: 'USD' },
cellAttributes: { alignment: 'left' }
}
];A url column can show a label that differs from the link target. The fieldName supplies the URL, and typeAttributes.label names the field that supplies the visible text:
{
label: 'Website',
fieldName: 'websiteUrl',
type: 'url',
typeAttributes: { label: { fieldName: 'websiteLabel' }, target: '_blank' }
}Notice that typeAttributes values can be objects of the form { fieldName: '...' }. This reads a value from each row, so the setting can vary by row.
Handling events
The datatable communicates through events. The most useful ones are:
onrowselection, which fires when the selected rows change.onsort, which fires when a user clicks a sortable header.onrowaction, which fires when a user chooses a row action or clicks a button column.onsave, which fires when a user saves inline edits.
Row selection
The onrowselection event carries the selected rows in event.detail.selectedRows.
<template>
<lightning-datatable
key-field="id"
data={contacts}
columns={columns}
onrowselection={handleRowSelection}
></lightning-datatable>
<p class="slds-var-m-top_small">Selected: {selectedCount}</p>
</template>import { LightningElement } from 'lwc';
export default class SelectableTable extends LightningElement {
columns = [{ label: 'Name', fieldName: 'name' }];
contacts = [
{ id: '1', name: 'Ada Lovelace' },
{ id: '2', name: 'Grace Hopper' }
];
selectedCount = 0;
handleRowSelection(event) {
const selectedRows = event.detail.selectedRows;
this.selectedCount = selectedRows.length;
}
}To preselect rows, set selected-rows to an array of key-field values, not an array of row objects.
Sorting
The datatable shows the sort arrow but does not reorder rows. You must sort the array and assign it back. Set sorted-by and sorted-direction so the header shows the current state.
<template>
<lightning-datatable
key-field="id"
data={contacts}
columns={columns}
sorted-by={sortedBy}
sorted-direction={sortedDirection}
onsort={handleSort}
hide-checkbox-column
></lightning-datatable>
</template>import { LightningElement } from 'lwc';
export default class SortableTable extends LightningElement {
columns = [
{ label: 'Name', fieldName: 'name', sortable: true },
{ label: 'City', fieldName: 'city', sortable: true }
];
contacts = [
{ id: '1', name: 'Grace Hopper', city: 'New York' },
{ id: '2', name: 'Ada Lovelace', city: 'London' }
];
sortedBy;
sortedDirection = 'asc';
handleSort(event) {
const { fieldName, sortDirection } = event.detail;
const factor = sortDirection === 'asc' ? 1 : -1;
this.contacts = [...this.contacts].sort(
(a, b) => factor * String(a[fieldName]).localeCompare(String(b[fieldName]))
);
this.sortedBy = fieldName;
this.sortedDirection = sortDirection;
}
}The handler copies the array with the spread operator before sorting. Sorting this.contacts in place would mutate the array that the template received, and the datatable would not necessarily notice the change. Assigning a new array makes the update reliable.
Row actions
An action column shows a menu on each row. Its typeAttributes.rowActions lists the menu items.
columns = [
{ label: 'Name', fieldName: 'name' },
{
type: 'action',
typeAttributes: {
rowActions: [
{ label: 'Show details', name: 'details' },
{ label: 'Delete', name: 'delete' }
]
}
}
];
handleRowAction(event) {
const actionName = event.detail.action.name;
const row = event.detail.row;
if (actionName === 'delete') {
this.contacts = this.contacts.filter((c) => c.id !== row.id);
}
}Wire it with onrowaction={handleRowAction} on the datatable. The event gives you the action name and the full row object, so you can act on the row without searching for it.
Inline editing
Set editable: true on a column to let users edit cells. Edited cells are marked as draft values. The datatable shows Save and Cancel buttons, and onsave fires with event.detail.draftValues, an array of objects that contain the key-field value and only the changed fields. Persist these changes yourself, for example through an Apex method or updateRecord. After a successful save, clear the drafts by setting the draft-values attribute to an empty array.
Common errors
- Missing or duplicate
key-fieldvalues. Rows render in the wrong order or selection jumps. Make sure every row has a unique value in that property. fieldNamethat does not match the data. The cell is empty. Compare the property names in the row objects with the column definitions, including case.- Wrong data types. A date column needs a date value or an ISO string, and a
numbercolumn needs a number. Strings with currency symbols render incorrectly. - Mutating the array in place. Calls such as
pushor an in-placesorton a tracked array may not refresh the table. Assign a new array. - Related fields from Apex or wire adapters. Records returned from the server nest related data, such as
Account.Name. ColumnfieldNamedoes not read nested paths, so flatten the rows first, as shown below.
const rows = records.map((record) => ({
...record,
accountName: record.Account ? record.Account.Name : ''
}));- Setting a fixed table height. The datatable does not size itself to its content in a scroll container. Wrap it in a
divwith a height andoverflowif you need a scrolling table, or usemax-heighton the wrapper.
Customizing appearance
The datatable renders inside base component markup that you cannot reach with ordinary selectors. Use cellAttributes for per-cell classes and alignment, and use styling hooks where the datatable documents them. The earlier chapters on styling hooks and style scoping explain why overriding internal classes is unreliable.
For accessibility, give the table a meaningful context. Place it in a lightning-card with a title, and make column labels descriptive. A column with an empty label needs a hidden label so that screen readers can announce it, which you can set through hideLabel: true on the column definition.
Exercise
A user clicks the "Name" header on a sortable lightning-datatable. The arrow appears, but the rows stay in the same order. What is missing, and what must the onsort handler do?
Show answer
The datatable only reports the click. It does not sort. The onsort handler must read fieldName and sortDirection from event.detail, sort a copy of the data array, assign the new array back to the property bound to data, and set sortedBy and sortedDirection so the header shows the state.
Exercise
Your rows come from Apex and each contains Account: { Name: 'Acme' }. A column with fieldName: 'Account.Name' shows empty cells. How do you fix it?
Show answer
The fieldName does not resolve nested paths. Flatten each row before assigning it to data, for example with accountName: record.Account ? record.Account.Name : '', and set the column's fieldName to accountName.