Introduction
The lightning-datatable component in LWC is a powerful way to display records in a structured table format with built-in features like sorting, inline editing, pagination, and row selection.
Key Features of lightning-datatable
- Displays data in a tabular format.
- Supports column sorting.
- Allows inline editing.
- Supports row selection and actions.
- Handles pagination and infinite loading.
Basic lightning-datatable Example
Fetching and Displaying Account Data
Apex Class (AccountController.cls)
@AuraEnabled(cacheable=true)
public static List<Account> getAccounts() {
return [SELECT Id, Name, Industry, Phone FROM Account LIMIT 10];
}
LWC JavaScript (accountTable.js)
import { LightningElement, wire, track } from 'lwc';
import getAccounts from '@salesforce/apex/AccountController.getAccounts';
const columns = [
{ label: 'Account Name', fieldName: 'Name', type: 'text' },
{ label: 'Industry', fieldName: 'Industry', type: 'text' },
{ label: 'Phone', fieldName: 'Phone', type: 'phone' }
];
export default class AccountTable extends LightningElement {
@track data = [];
@track columns = columns;
@track error;
@wire(getAccounts)
wiredAccounts({ error, data }) {
if (data) {
this.data = data;
this.error = undefined;
} else if (error) {
this.error = error;
this.data = undefined;
}
}
}
LWC HTML (accountTable.html)
<template>
<template if:true={data}>
<lightning-datatable
key-field="Id"
data={data}
columns={columns}
hide-checkbox-column="true">
</lightning-datatable>
</template>
<template if:true={error}>
<p>Error fetching records.</p>
</template>
</template>
Explanation:
- Calls Apex to fetch Account records.
- Defines table columns in JavaScript.
- Binds data to
lightning-datatable.
Sorting in lightning-datatable
lightning-datatable allows sorting based on column values.
Example: Sorting Accounts by Name
LWC JavaScript (sortableTable.js)
import { LightningElement, wire, track } from 'lwc';
import getAccounts from '@salesforce/apex/AccountController.getAccounts';
const columns = [
{ label: 'Account Name', fieldName: 'Name', type: 'text', sortable: true },
{ label: 'Industry', fieldName: 'Industry', type: 'text', sortable: true },
];
export default class SortableTable extends LightningElement {
@track data = [];
@track columns = columns;
@track sortBy;
@track sortDirection = 'asc';
@wire(getAccounts)
wiredAccounts({ error, data }) {
if (data) {
this.data = data;
}
}
handleSort(event) {
const { fieldName, sortDirection } = event.detail;
this.sortBy = fieldName;
this.sortDirection = sortDirection;
this.sortData(fieldName, sortDirection);
}
sortData(fieldname, direction) {
let parseData = JSON.parse(JSON.stringify(this.data));
let isReverse = direction === 'asc' ? 1 : -1;
parseData.sort((a, b) => {
return a[fieldname] > b[fieldname] ? isReverse : -1 * isReverse;
});
this.data = parseData;
}
}
LWC HTML (sortableTable.html)
<template>
<lightning-datatable
key-field="Id"
data={data}
columns={columns}
sorted-by={sortBy}
sorted-direction={sortDirection}
onsort={handleSort}>
</lightning-datatable>
</template>
Explanation:
- Adds
sortable: trueto columns. - Handles sorting with
handleSort(). - Sorts data dynamically using JavaScript.
Inline Editing in lightning-datatable
Users can edit records directly in the table.
Example: Editing Account Phone Field
LWC JavaScript (editableTable.js)
import { LightningElement, track, wire } from 'lwc';
import getAccounts from '@salesforce/apex/AccountController.getAccounts';
import { updateRecord } from 'lightning/uiRecordApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
const columns = [
{ label: 'Account Name', fieldName: 'Name', type: 'text' },
{ label: 'Phone', fieldName: 'Phone', type: 'phone', editable: true }
];
export default class EditableTable extends LightningElement {
@track data = [];
@track columns = columns;
@wire(getAccounts)
wiredAccounts({ data }) {
if (data) {
this.data = data;
}
}
handleSave(event) {
const fields = event.detail.draftValues[0];
const recordInput = { fields };
updateRecord(recordInput)
.then(() => {
this.dispatchEvent(new ShowToastEvent({
title: 'Success',
message: 'Record Updated',
variant: 'success'
}));
})
.catch(error => {
console.error(error);
});
}
}
LWC HTML (editableTable.html)
<template>
<lightning-datatable
key-field="Id"
data={data}
columns={columns}
onsave={handleSave}
draft-values={draftValues}
hide-checkbox-column="true"
editable>
</lightning-datatable>
</template>
Explanation:
- Sets
editable: truefor fields. - Uses
onsaveevent to update records usingupdateRecord(). - Shows success toast message upon update.
Conclusion
- Use
lightning-datatablefor structured data display. - Enable sorting for a better user experience.
- Allow inline editing for quick updates.
- Implement row selection and actions to handle record interactions.
In the next post, we will explore Lightning Message Service (LMS).
Stay tuned! 🚀

