Sub topic 1
What lightning-datatable does
Prerequisites
This chapter assumes you already know the following:
- Basic Lightning Web Components (LWC): templates, the
@wiredecorator, and event handlers. - JavaScript arrays, objects, and destructuring.
- How to wire an Apex method or a Lightning Data Service adapter to a component.
- Salesforce objects and fields, such as Contact and its Name and Email fields.
You do not need to know anything about lightning-datatable itself. This chapter introduces what it is, how it is built, and when to pick it. Later chapters cover each feature in detail.
What the component is
lightning-datatable is a base component from the Lightning Component Library. It renders an HTML table of records with typed columns. A base component is a component that Salesforce ships, so you use it in a template without writing or importing it.
You give the table two required pieces of information: the rows to show and a description of the columns. It then handles the following for you:
- Header cells with labels.
- Cell formatting based on a column type, such as email links, phone links, dates, and currency.
- Optional features that you switch on: sorting indicators, row selection, row actions, inline editing, column resizing, and loading more rows on scroll.
Each feature follows one pattern. You describe the behavior with attributes or column properties. The table raises an event when the user interacts with it. Your component handles the event and updates its own state. The table does not change your data. It reports what the user did.
When to use it
Use lightning-datatable when you want a read-mostly grid of records in which every row has the same shape. Typical cases are a list of related contacts on an account page, a result list from a search, or a small admin screen with edit and delete actions.
Consider another approach in these cases:
| Need | Better choice |
|---|---|
| A standard list of records with no custom logic | A list view or a related list, which need no code |
| A hierarchy of parent and child rows | `lightning-tree-grid` |
| Each row needs rich, custom layout such as cards or images | Your own template with `for:each` |
| Very large data sets, such as thousands of rows at once | Paging or infinite loading, covered in a later chapter |
| A cell needs a UI that no built-in type offers | A custom column type, covered in the last chapter |
The base component gives you consistent styling, keyboard navigation, and accessibility support. Building the same table by hand costs much more work than using it.
The three core attributes
A minimal table needs three attributes.
| Attribute | Purpose |
|---|---|
| `data` | The array of row objects to display. |
| `columns` | An array of column definitions that says which field goes in which column and how to format it. |
| `key-field` | The name of the field whose value is unique for each row. |
The next chapters explain data and key-field and the column definitions one at a time. For now, the main idea is that the table reads from two arrays. Each object in data is one row. Each object in columns is one column. A column's fieldName property says which property of each row object to show.
A first complete example
The example below shows Contact records in a table. It has three parts: an Apex method, a JavaScript class, and a template.
The Apex method returns the rows. It is marked cacheable=true so it can be used with @wire. It also selects Id, because the table needs that field as its key.
public with sharing class ContactController {
@AuraEnabled(cacheable=true)
public static List<Contact> getContacts() {
return [
SELECT Id, Name, Email, Phone, Birthdate
FROM Contact
WITH USER_MODE
ORDER BY Name
LIMIT 50
];
}
}WITH USER_MODE makes the query respect the running user's field-level security and sharing. The LIMIT 50 keeps the first version small.
The JavaScript class defines the columns and wires the Apex method.
import { LightningElement, wire } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';
const COLUMNS = [
{ label: 'Name', fieldName: 'Name', type: 'text', sortable: true },
{ label: 'Email', fieldName: 'Email', type: 'email' },
{ label: 'Phone', fieldName: 'Phone', type: 'phone' },
{ label: 'Birthdate', fieldName: 'Birthdate', type: 'date-local' }
];
export default class ContactTable extends 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 = [];
}
}
}Three details are worth noting:
- The
COLUMNSconstant lives outside the class. The column definitions do not change, so one shared array is enough. - The wired function receives the whole result object. It saves that object in
wiredResultso a later chapter can pass it torefreshApex. datastarts as an empty array. The table then renders with no rows until the wire delivers records, and it never receivesundefined.
The template binds the pieces together.
<template>
<lightning-card title="Contacts" icon-name="standard:contact">
<lightning-datatable
key-field="Id"
data={data}
columns={columns}
hide-checkbox-column>
</lightning-datatable>
</lightning-card>
</template>key-field="Id" names the property that identifies each row. The hide-checkbox-column attribute removes the selection checkboxes, because this first table does not use selection.
The sortable: true flag on the Name column makes the header clickable. Clicking it only fires a sort event. Nothing is reordered until your component handles that event. A later chapter shows how to do that.
How the data flows
The diagram shows the path from the database to the screen.
The arrows from the table back to the component show the pattern from earlier. The table raises events such as sort, rowselection, rowaction, and save. Your handlers decide what to do and update component state. Changing data makes the table render again.
What the table does not do
Knowing the limits early prevents wrong assumptions.
- It does not fetch data. You supply
datafrom Apex, a wire adapter, or any other source. - It does not sort, filter, or page the data for you. It shows indicators and raises events. Your code changes the array.
- It does not save edits. Inline editing collects draft values and raises a
saveevent. You callupdateRecordor Apex yourself. - It does not mutate
data. Wired data is read-only, so sorting must work on a copy, such as[...this.data]. - It does not wrap long text by default. Cell text is truncated unless you configure the column.
Common errors
These problems appear often in a first table.
- The table is empty but no error shows. Check that every
fieldNamematches the property name in the row objects exactly, including case. A column whose field is missing from the row renders blank cells. Also confirm the Apex query selects the field. - The console warns about a missing or duplicate key.
key-fieldmust name a field that exists on every row and has a unique value on each. If the query leaves outId, the table cannot identify rows. - Columns appear but the headers have no text. Each column needs a
label. Without it the header is empty. - The Apex method does not run through the wire. A method used with
@wiremust be annotated@AuraEnabled(cacheable=true). - A relationship field shows nothing. The row object holds nested data, such as
Account.NameinsideAccount. A column withfieldName: 'Account.Name'does not read it. You flatten the row first, for example by copyingrow.Account.Nameto a top-level property. This is a frequent source of confusion.
A mental model to carry forward
Treat lightning-datatable as a display and an event source. Your component owns the state: the rows, the sort order, the selection, and the edits. The table shows that state and tells you what the user tried to change. If you keep this separation in mind, each feature in the following chapters becomes a small variation on one pattern: set an attribute, listen for an event, update state.
Exercise
A teammate builds a table with data={data} and columns={columns} but leaves out key-field. The Apex query selects Name and Email only. List two things that are wrong, and say what you would change.
Show answer
First, the table has no key-field, so it cannot give each row a unique identity. Add key-field="Id". Second, the query does not select Id, so the rows would have no unique value for that field even if the attribute were present. Add Id to the SELECT list in the Apex method.
Exercise
The user clicks the sortable Name header in the example table, and the arrow icon appears, but the rows stay in the same order. Why, and what is the fix at a high level?
Show answer
The table only raises a sort event. It does not reorder the rows itself. Add an onsort handler to the template that sorts a copy of data and assigns it back to this.data. Also store the field and direction in sortedBy and sortedDirection and bind them to sorted-by and sorted-direction.