Sub topic 3
Defining columns
This chapter covers the columns attribute of lightning-datatable. It assumes you can write a basic Lightning Web Component, read JavaScript arrays and objects, and wire an Apex method to a component. The previous chapter covered data and key-field. Here you learn how each column definition connects to the data.
What a column definition is
The columns attribute takes an array of plain JavaScript objects. Each object describes one column. The table creates one column for each object, in array order, from left to right.
Three properties do most of the work:
| Property | Purpose | Notes |
|---|---|---|
| `label` | The text in the column header | A string. Use `''` for no visible text. |
| `fieldName` | The property to read from each row object | Must match the property name in `data` exactly, including case. |
| `type` | How the value is rendered | Defaults to `text` when omitted. |
The table does not know your data's shape. It takes each row object from data, reads the property named by fieldName, and renders the value according to type.
A minimal set of columns
This is the column array used in the running Contact example. It sits in a module-level constant outside the class.
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' }
];Each object uses the same three core properties. sortable: true on the Name column is an extra option. A later chapter covers it.
Here is the full component. It combines the columns with the cacheable Apex method from earlier in the tutorial.
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 = [];
}
}
}The template binds both attributes.
<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>The three core properties in detail
label
The label is the header text. The table does not read it from the Salesforce field definition, so it never appears automatically. You write it yourself. Because it is a plain string, you can translate it by importing a custom label and using the imported value.
If you leave label out, the column still renders, but its header is blank. This is how you build a narrow action column, as in the row actions chapter.
fieldName
fieldName is the property name on each row object. It is not a SOQL field reference. The two usually match because Apex returns each record as an object with the queried field names as properties. They stop matching in these cases:
- You rename or compute properties in JavaScript before passing
datato the table. - You query a relationship field such as
Account.Name. - You return a wrapper class from Apex whose property names differ from the field names.
When fieldName matches no property, the table shows an empty cell. It does not throw an error and does not log a warning. A blank column with a correct header is the typical symptom of a typo or a case mismatch (name instead of Name).
type
type selects the renderer. Omitting it gives text. The next chapter covers the built-in types and their typeAttributes in detail. For now, treat type as a formatting instruction applied to the value that fieldName found. It does not convert the data. A date-local column expects a value that JavaScript can read as a date, such as the YYYY-MM-DD string that Apex returns for a Date field.
Relationship fields need flattening
fieldName takes a single property name. A value like 'Account.Name' is not followed down into a nested object. If your query returns Account.Name, the row object looks like this:
{ Id: '003...', Name: 'Ada Lovelace', Account: { Name: 'Analytical Engines' } }A column with fieldName: 'Account.Name' shows an empty cell. The fix is to copy the nested value to a top-level property and point the column at the new name.
This component assumes an Apex method named getContactsWithAccount that selects Account.Name and has the same cacheable signature as getContacts.
import { LightningElement, wire } from 'lwc';
import getContactsWithAccount from '@salesforce/apex/ContactController.getContactsWithAccount';
const COLUMNS = [
{ label: 'Name', fieldName: 'Name' },
{ label: 'Account', fieldName: 'AccountName' }
];
export default class ContactAccountTable extends LightningElement {
columns = COLUMNS;
data = [];
@wire(getContactsWithAccount)
wiredContacts({ data, error }) {
if (data) {
this.data = data.map((contact) => ({
...contact,
AccountName: contact.Account?.Name
}));
} else if (error) {
this.data = [];
}
}
}The spread creates a new object for each row. This matters because the objects the wire service provides are read-only, so you cannot add AccountName to them directly. The optional chaining ?. keeps contacts without an account from throwing an error.
Columns that have no fieldName
Some columns do not display a field value, so they need no fieldName. The action type is the main example. It renders a menu of row actions, and its list lives in typeAttributes.
const COLUMNS = [
{ label: 'Name', fieldName: 'Name' },
{
type: 'action',
typeAttributes: {
rowActions: [
{ label: 'View', name: 'view' },
{ label: 'Delete', name: 'delete' }
]
}
}
];The row actions chapter covers the handler. The point for now is that fieldName is required only when the column reads a value from the row.
Static versus dynamic column arrays
For most tables, a module-level constant is the right choice. The array is created once and never changes. Assigning it to columns = COLUMNS in the class is enough.
Use a getter or a method when the definitions depend on runtime state, for example:
- Labels that come from imported custom labels.
- Columns that depend on user permissions or on an object chosen by the user.
- A flag that adds or removes an editable column.
get columns() {
const base = [
{ label: 'Name', fieldName: 'Name' },
{ label: 'Email', fieldName: 'Email', type: 'email' }
];
if (this.showPhone) {
base.push({ label: 'Phone', fieldName: 'Phone', type: 'phone' });
}
return base;
}A getter is re-evaluated when a tracked value it uses changes. If you keep columns as a field and want to change it, assign a new array. Pushing onto the existing array or editing one of its objects in place can fail to refresh the table.
this.columns = this.columns.filter((col) => col.fieldName !== 'Phone');Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Header shows, every cell is empty | `fieldName` does not match a row property, or the case differs | Compare it with the keys in one row object, for example with `console.log(JSON.stringify(this.data[0]))`. |
| Relationship column is blank | Dot notation in `fieldName` | Flatten the value into a top-level property. |
| Date column shows odd text | The value is not a date string or timestamp | Return a `Date` field, or convert the value before passing it. |
| Column change does not appear | The array was edited in place | Assign a new array to `columns`. |
| Header is blank | `label` is missing | Add a `label`. |
Choosing what to put in a column definition
Keep the definition to what the column needs now. A column with only label and fieldName is a complete, valid definition. Add type when the default text rendering does not suit the value. Add the other options as the feature calls for them: sortable, editable, typeAttributes, cellAttributes, initialWidth. Later chapters introduce each one. Column definitions are plain data, so putting them in a separate JavaScript module is also fine when several components share a layout.
Exercise
A component queries Contacts with SELECT Id, Name, Account.Name FROM Contact and passes the result straight to lightning-datatable. The column { label: 'Account', fieldName: 'Account.Name' } shows empty cells, while the Name column works. Explain why, and write the code that fixes it.
Show answer
fieldName is read as a single property name on each row object. The table does not follow a dotted path into the nested Account object, so it finds nothing and shows an empty cell without raising an error. Copy the nested value to a top-level property when you receive the data, then point the column at it:
this.data = data.map((contact) => ({ ...contact, AccountName: contact.Account?.Name }));
and change the column to { label: 'Account', fieldName: 'AccountName' }. The spread creates a new object because the wired row objects are read-only.
Exercise
A component declares columns = COLUMNS;. A button handler runs this.columns.push({ label: 'Phone', fieldName: 'Phone', type: 'phone' });, but the Phone column does not appear. What should the handler do instead?
Show answer
Assign a new array so the component sees a changed value, for example this.columns = [...this.columns, { label: 'Phone', fieldName: 'Phone', type: 'phone' }];. Editing the existing array in place does not reliably trigger a re-render.