Sub topic 1
What `lightning-datatable` Does
Prerequisites
This chapter assumes you know basic Lightning Web Components, JavaScript arrays and objects, Apex methods, and Salesforce record fields.
What `lightning-datatable` Does
lightning-datatable is a base Lightning component that renders records in rows and fields in columns. It provides standard behavior such as scrolling, column labels, formatting, sorting events, row selection, and inline editing.
The component does not query Salesforce by itself. Your component supplies the records through data and describes their columns through columns.
Passing Data and a Key-Field
data is an array of objects. Each object represents one row. key-field names the property that uniquely identifies each row. For Salesforce records, use Id in the data and set key-field="Id".
<template>
<lightning-card title="Contacts">
<lightning-datatable
key-field="Id"
data={data}
columns={columns}
hide-checkbox-column>
</lightning-datatable>
</lightning-card>
</template>A missing or incorrect key field causes unstable row behavior. The value must exist on every row and must be unique. Do not use a display value such as Name, because multiple records can share it.
An empty array renders an empty table. Keep the data array empty while records load, then replace it with the returned records. Handle errors separately so a failed query does not look like a valid empty result.
Defining Columns
A column definition connects a visible label to a property in each row. fieldName must match the JavaScript property name exactly. type controls formatting and default behavior.
const COLUMNS = [
{ label: 'Name', fieldName: 'Name', type: 'text' },
{ 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 = [];
}Use built-in types whenever they represent the value correctly. Later chapters add attributes for links, currency, alignment, and other behavior.
Exercise
What must be true about the value named by key-field?
Show answer
It must exist on every row and uniquely identify that row.