LearnFrenzy
Sign in Take a free test

Datatables, Modals and Navigation · Lesson 19 of 25

lightning-datatable in LWC: Sorting, Row Actions, Inline Edit

6 min read Updated Nov 8, 2026 Saurabh Samir

Tables are the backbone of business UI: lists of opportunities, cases, invoices. lightning-datatable gives you a Salesforce-styled, accessible, responsive table with typed columns, sorting, row selection, row-level actions and inline editing – you supply columns and data, and handle a few events.

In this lesson

  • Columns, data and key-field
  • Sorting
  • Row actions
  • Inline editing and saving draft values

Columns and data

<!-- dealTable.html -->
<template>
    <lightning-card title={title}>
        <lightning-datatable
            key-field="Id"
            data={rows}
            columns={columns}
            sorted-by={sortedBy}
            sorted-direction={sortDirection}
            onsort={handleSort}
            onrowaction={handleRowAction}
            draft-values={draftValues}
            onsave={handleSave}
            hide-checkbox-column>
        </lightning-datatable>
        <p>{lastAction}</p>
    </lightning-card>
</template>
// dealTable.js
import { LightningElement, api } from 'lwc';

const ACTIONS = [
    { label: 'Mark won', name: 'mark_won' },
    { label: 'Delete', name: 'delete' },
];

const COLUMNS = [
    { label: 'Deal', fieldName: 'Name', sortable: true },
    { label: 'Stage', fieldName: 'StageName', editable: true },
    { label: 'Amount', fieldName: 'Amount', type: 'currency', sortable: true, typeAttributes: { currencyCode: 'USD' } },
    { label: 'Close date', fieldName: 'CloseDate', type: 'date', sortable: true },
    { type: 'action', typeAttributes: { rowActions: ACTIONS } },
];

export default class DealTable extends LightningElement {
    @api deals = [
        { Id: '006A', Name: 'Acme renewal', StageName: 'Negotiation', Amount: 120000, CloseDate: '2026-12-15' },
        { Id: '006B', Name: 'Globex expansion', StageName: 'Proposal', Amount: 45000, CloseDate: '2026-11-30' },
        { Id: '006C', Name: 'Initech pilot', StageName: 'Prospecting', Amount: 8000, CloseDate: '2027-01-20' },
    ];
    columns = COLUMNS;
    rows = [];
    sortedBy;
    sortDirection = 'asc';
    draftValues = [];
    lastAction = '';

    connectedCallback() {
        this.rows = [...this.deals];                      // a private copy we can sort and change
    }

    get title() {
        return `Pipeline (${this.rows.length})`;
    }

    handleSort(event) {
        const { fieldName, sortDirection } = event.detail;
        const dir = sortDirection === 'asc' ? 1 : -1;
        this.rows = [...this.rows].sort((a, b) => (a[fieldName] > b[fieldName] ? dir : a[fieldName] < b[fieldName] ? -dir : 0));
        this.sortedBy = fieldName;
        this.sortDirection = sortDirection;
    }

    handleRowAction(event) {
        const { action, row } = event.detail;
        if (action.name === 'mark_won') {
            this.rows = this.rows.map((r) => (r.Id === row.Id ? { ...r, StageName: 'Closed Won' } : r));
            this.lastAction = `${row.Name} marked as won`;
        } else if (action.name === 'delete') {
            this.rows = this.rows.filter((r) => r.Id !== row.Id);
            this.lastAction = `${row.Name} deleted`;
        }
    }

    handleSave(event) {
        const changes = event.detail.draftValues;         // [{ Id, StageName }, …] – only edited cells
        this.rows = this.rows.map((r) => ({ ...r, ...changes.find((c) => c.Id === r.Id) }));
        this.draftValues = [];                             // clear the yellow "edited" state
        this.lastAction = `${changes.length} row(s) saved`;
    }
}

Result after sorting, row actions and an inline edit

▌Pipeline (3)
Deal | Stage | Amount | Close date
Acme renewal | Negotiation | $120,000.00 | 2026-12-15 | ⋮
Globex expansion | Proposal | $45,000.00 | 2026-11-30 | ⋮
Initech pilot | Prospecting | $8,000.00 | 2027-01-20 | ⋮

› sort by Amount (asc)
▌Pipeline (3)
Deal | Stage | Amount | Close date
Initech pilot | Prospecting | $8,000.00 | 2027-01-20 | ⋮
Globex expansion | Proposal | $45,000.00 | 2026-11-30 | ⋮
Acme renewal | Negotiation | $120,000.00 | 2026-12-15 | ⋮

› row action “mark_won” on row 2
▌Pipeline (3)
Deal | Stage | Amount | Close date
Initech pilot | Prospecting | $8,000.00 | 2027-01-20 | ⋮
Globex expansion | Closed Won | $45,000.00 | 2026-11-30 | ⋮
Acme renewal | Negotiation | $120,000.00 | 2026-12-15 | ⋮
Globex expansion marked as won

› row action “delete” on row 1
▌Pipeline (2)
Deal | Stage | Amount | Close date
Globex expansion | Closed Won | $45,000.00 | 2026-11-30 | ⋮
Acme renewal | Negotiation | $120,000.00 | 2026-12-15 | ⋮
Initech pilot deleted

› inline edit saved: [{"Id":"006A","StageName":"Closed Won"}]
▌Pipeline (2)
Deal | Stage | Amount | Close date
Globex expansion | Closed Won | $45,000.00 | 2026-11-30 | ⋮
Acme renewal | Closed Won | $120,000.00 | 2026-12-15 | ⋮
1 row(s) saved
  • key-field names the unique field of each row – the record Id.
  • Column type controls formatting and editing: text, number, currency, percent, date, email, phone, url, boolean, button, action.
  • The datatable doesn't sort data itself: it fires sort, you sort, and you pass back sorted-by and sorted-direction so the header arrow shows.
  • Row actions arrive in rowaction with the action's name and the full row.
  • Inline edits collect as draft values containing only the changed fields plus the key field. On save, persist them and reset draftValues.

Saving inline edits to Salesforce

In a real component, handleSave saves through LDS and then refreshes the list:

import { updateRecord } from 'lightning/uiRecordApi';
import { refreshApex } from '@salesforce/apex';

async handleSave(event) {
    const records = event.detail.draftValues.map((draft) => ({ fields: { ...draft } }));   // each draft has Id
    try {
        await Promise.all(records.map((r) => updateRecord(r)));
        this.draftValues = [];
        await refreshApex(this.wiredDeals);            // reload the rows from Apex
    } catch (error) {
        this.errors = { table: { title: 'Some rows failed', messages: [error.body?.message] } };   // shown by the table
    }
}

For many rows, a single Apex method that updates a list in one DML statement is more efficient than one updateRecord per row.

Datatable tips

  • Flatten relationship fields before passing data (Account.Name → AccountName); columns can't read nested paths.
  • For long lists, enable enable-infinite-loading and load more rows in onloadmore instead of loading everything.
  • Use a url column with typeAttributes: { label: { fieldName: 'Name' } } to link each row to its record.

Practice

Try it yourself

  1. Show three cases in a datatable with Subject, Priority and a "Close" row action that removes the row and shows "Closed: subject".

    Show solution
    <!-- caseTable.html -->
    <template>
        <lightning-datatable key-field="Id" data={rows} columns={columns} onrowaction={handleRowAction} hide-checkbox-column></lightning-datatable>
        <p>{message}</p>
    </template>
    // caseTable.js
    import { LightningElement } from 'lwc';
    
    export default class CaseTable extends LightningElement {
        columns = [
            { label: 'Subject', fieldName: 'Subject' },
            { label: 'Priority', fieldName: 'Priority' },
            { type: 'action', typeAttributes: { rowActions: [{ label: 'Close', name: 'close' }] } },
        ];
        rows = [
            { Id: '500A', Subject: 'Login issue', Priority: 'High' },
            { Id: '500B', Subject: 'Invoice missing', Priority: 'Medium' },
            { Id: '500C', Subject: 'Feature request', Priority: 'Low' },
        ];
        message = '';
    
        handleRowAction(event) {
            const { row } = event.detail;
            this.rows = this.rows.filter((r) => r.Id !== row.Id);
            this.message = `Closed: ${row.Subject}`;
        }
    }

    Result

    Subject | Priority
    Login issue | High | ⋮
    Invoice missing | Medium | ⋮
    Feature request | Low | ⋮
    
    › row action “close” on row 1
    Subject | Priority
    Invoice missing | Medium | ⋮
    Feature request | Low | ⋮
    Closed: Login issue

Quick check

Does lightning-datatable sort data for you?

No – handle onsort, sort the array, and set sorted-by and sorted-direction.

What do draft values contain?

Only the edited fields of each changed row, plus the key field.

Can a column show Account.Name directly?

No – flatten it into a top-level field first.

Summary

  • lightning-datatable needs key-field, data and typed columns.
  • Handle sort, rowaction and save events; the table reports, you change the data.
  • Save draft values through LDS or Apex, then refresh and clear the drafts.

Finished this lesson?

Mark it complete to track your progress, then carry on with the next lesson.

Next lesson

Search LearnFrenzy

Esc

Quick links