Sub topic 14
Extending the table with custom column types
This chapter assumes you have built the contact table from the earlier chapters. You should know how columns, typeAttributes, and cellAttributes work. You should also be comfortable with child components that use @api properties.
When the built-in types are not enough
lightning-datatable ships with a fixed set of column types, such as text, date-local, url, button, and action. Most needs are covered by combining these with typeAttributes and cellAttributes. A custom type is for the cases where no combination works. Examples are a colored status badge, a rating shown as stars, or a picklist that edits in place.
Try the built-in options first, because a custom type adds files, a subclass, and maintenance.
| Need | Try first | Custom type needed? |
|---|---|---|
| Link with different visible text | `url` with `typeAttributes.label` | No |
| Icon next to a value | `cellAttributes.iconName` | No |
| Conditional CSS class on a cell | `cellAttributes.class` with a field reference | No |
| Clickable button in a cell | `button` or `button-icon` | No |
| Arbitrary markup or a child component in a cell | None | Yes |
| Custom editor, such as a picklist | None | Yes, with an edit template |
How custom types work
You cannot change lightning-datatable itself. Instead, you create a new component that extends it and registers extra types. Your template then uses <c-my-datatable> in place of <lightning-datatable>. All the attributes and events you already know still work.
Each custom type needs three parts:
- A name, which is the string you put in a column's
type. - An HTML-only template file. It describes what one cell contains.
- Optionally, a child component that the template renders.
The diagram shows how a cell value reaches the screen.
A worked example: a status badge
The example shows each Contact's lead source as a colored badge. First, add LeadSource to the SOQL query from the Apex chapter:
public with sharing class ContactController {
@AuraEnabled(cacheable=true)
public static List<Contact> getContacts() {
return [
SELECT Id, Name, Email, Phone, Birthdate, LeadSource
FROM Contact
WITH USER_MODE
ORDER BY Name
LIMIT 50
];
}
}Step 1: the child component
The child component is a normal LWC. It receives the cell value and a tone through @api properties.
<template>
<span class={badgeClass}>{value}</span>
</template>import { LightningElement, api } from 'lwc';
export default class StatusBadge extends LightningElement {
@api value;
@api tone = 'success';
get badgeClass() {
return `slds-badge slds-theme_${this.tone}`;
}
}Step 2: the type template
Create statusBadge.html inside the folder of the extended datatable (created in step 3). It has no JavaScript class. It is only markup that the datatable loads for each cell.
<template>
<c-status-badge
value={value}
tone={typeAttributes.tone}>
</c-status-badge>
</template>Two names are available inside a type template:
valueis the cell's value, read from the column'sfieldName.typeAttributesholds the attributes you declared for the type. Read each one astypeAttributes.name.
Step 3: the extended datatable
Create a component named customDatatable. Its folder holds the JavaScript file and statusBadge.html.
import LightningDatatable from 'lightning/datatable';
import statusBadgeTemplate from './statusBadge.html';
export default class CustomDatatable extends LightningDatatable {
static customTypes = {
statusBadge: {
template: statusBadgeTemplate,
standardCellLayout: true,
typeAttributes: ['tone']
}
};
}The component needs no HTML file of its own, because it inherits the datatable's template. It does need a customDatatable.js-meta.xml file, as every component does:
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>61.0</apiVersion>
<isExposed>false</isExposed>
</LightningComponentBundle>The registration object has three keys:
templateis the imported template file.standardCellLayoutcontrols the wrapper around your markup.typeAttributeslists every attribute name the type accepts. An attribute missing from this list is not passed to the template.
Step 4: use it in the table
In the parent, swap the tag and add a column that uses the new type.
<template>
<lightning-card title="Contacts" icon-name="standard:contact">
<c-custom-datatable
key-field="Id"
data={data}
columns={columns}
hide-checkbox-column>
</c-custom-datatable>
</lightning-card>
</template>const COLUMNS = [
{ label: 'Name', fieldName: 'Name', type: 'text', sortable: true },
{ label: 'Email', fieldName: 'Email', type: 'email' },
{
label: 'Lead source',
fieldName: 'LeadSource',
type: 'statusBadge',
typeAttributes: { tone: 'success' }
}
];The wire, the sort handler, and the other parts of the parent component stay the same.
Per-row type attributes
A type attribute can point at a field on the row instead of holding a fixed value. The datatable resolves it separately for every row, as it does for built-in types.
{
label: 'Lead source',
fieldName: 'LeadSource',
type: 'statusBadge',
typeAttributes: { tone: { fieldName: 'badgeTone' } }
}The badgeTone field must exist on each row object. Wired Apex data is read-only, so build new row objects when you load the data:
this.data = data.map((row) => ({
...row,
badgeTone: row.LeadSource === 'Web' ? 'success' : 'warning'
}));Standard cell layout
standardCellLayout decides who is responsible for the cell's frame.
- With
true, the datatable wraps your markup in its normal cell container. Padding, truncation, andcellAttributessuch asalignmentandclassstill apply. Choose this for most types. - With
false, your template fills the whole cell. You handle padding and alignment yourself. Choose this when the content needs the full cell area, such as a button that spans it.
Edge cases and gotchas
- Names must be unique. Do not reuse a built-in type name such as
textorurl. - The template file is not a component. It cannot have JavaScript,
@apiproperties, or lifecycle hooks. Put logic in the child component. - Sorting uses the field value. The
sortevent reports the column'sfieldName. Your handler sorts the raw field, not the rendered badge. - Every attribute must be declared. If a template shows
undefinedfor a type attribute, check that its name is in thetypeAttributesarray. Also check that the spelling matches the column definition. - Events from the child component must be handled in the parent component's logic or re-dispatched. Cells render in a nested structure, so it is easy to lose an event if you do not set
bubblesandcomposedcorrectly. Test any click behavior in a real org. - Editing needs more work. To make a custom type editable, you also provide an
editTemplatein the type registration, with a child component that fires the change in the way the datatable expects. Plan that as a separate piece of work, not a quick addition. - Cost. A custom cell is a component instance per row. For long tables, keep the child component light.
Exercise
A priorityFlag custom type shows nothing for its level type attribute. The column has typeAttributes: { level: 'high' } and the template uses {typeAttributes.level}. The registration is { template: priorityTemplate, standardCellLayout: true }. What is missing, and what is the fix?
Show answer
The registration has no typeAttributes array, so the datatable does not pass level to the template. Add typeAttributes: ['level'] to the priorityFlag entry in customTypes.
Exercise
You want the badge tone to depend on each contact's data, not to be the same for every row. Which two changes make this work?
Show answer
In the column definition, give the type attribute a field reference, such as typeAttributes: { tone: { fieldName: 'badgeTone' } }. Then add a badgeTone property to every row object, for example by mapping over the wired data into new objects, because the wired data is read-only.
Exercise
A teammate wants a cell that shows an icon beside text and turns red when a value is low. Do they need a custom type? Explain.
Show answer
No. cellAttributes supports iconName for the icon, and cellAttributes.class can take a field reference that holds a CSS class, so the red styling can be computed per row. A custom type is only needed if these options cannot produce the markup.