Sub topic 7
Sorting rows
This chapter assumes you have the ContactTable component from the earlier chapters. That means a columns array, a data property filled by a wire, and a key-field of Id. It also assumes you can write an LWC event handler.
How sorting works
lightning-datatable does not sort data itself. It shows a sort arrow in the header of each sortable column and fires a sort event when the user clicks it. Your component must reorder the rows and give the new array back to the table.
Three pieces make this work:
- A column marked
sortable: true. - An
onsorthandler that reordersdata. - The
sorted-byandsorted-directionattributes, which tell the table which arrow to display.
The table keeps no sort state of its own. If you skip the third piece, the rows still reorder, but the header shows no indicator.
Mark columns as sortable
Add sortable: true to each column that should respond to clicks. In the earlier column definitions, Name already has it:
const COLUMNS = [
{ label: 'Name', fieldName: 'Name', type: 'text', sortable: true },
{ label: 'Email', fieldName: 'Email', type: 'email' },
{ label: 'Birthdate', fieldName: 'Birthdate', type: 'date-local', sortable: true }
];Only Name and Birthdate show a clickable header here. The event reports the clicked column's fieldName, so that value must be a real key on your row objects.
Write the handler
The event's detail carries fieldName and sortDirection, which is either asc or desc.
sortedBy;
sortedDirection = 'asc';
handleSort(event) {
const { fieldName, sortDirection } = event.detail;
const factor = sortDirection === 'asc' ? 1 : -1;
this.data = [...this.data].sort((a, b) => {
const x = a[fieldName] ?? '';
const y = b[fieldName] ?? '';
return x > y ? factor : x < y ? -factor : 0;
});
this.sortedBy = fieldName;
this.sortedDirection = sortDirection;
}Two details matter here:
[...this.data]copies the array before sorting. Data from a wire is read-only, andsort()changes an array in place, so sorting the original can throw an error or fail silently.?? ''replacesnullandundefinedwith an empty string. Contacts without a birthdate would otherwise compare unpredictably.
Connect the template
<lightning-datatable
key-field="Id"
data={data}
columns={columns}
sorted-by={sortedBy}
sorted-direction={sortedDirection}
onsort={handleSort}>
</lightning-datatable>Binding sorted-by and sorted-direction to the properties you set in the handler is what draws the arrow.
Common errors
- The header is not clickable. The column lacks
sortable: true. - Clicking does nothing.
onsortis missing from the template, or the handler never assigns a new array todata. - The arrow appears on the wrong column.
sorted-bymust equal the column'sfieldName, not its label. - Text sorts oddly. The comparison is case-sensitive, so
"adams"sorts after"Zhou". Lower-case string values before comparing if that matters to your users.
Exercise
A user clicks the Birthdate header and the rows reorder, but no sort arrow appears. Which part of the code is most likely missing?
Show answer
The handler does not store the event's fieldName and sortDirection in properties bound to sorted-by and sorted-direction on the table. The table keeps no sort state, so the component must pass it back.
Exercise
Why does the handler sort [...this.data] and not this.data?
Show answer
Wired data is read-only, and Array.sort() changes the array in place. Sorting a copy avoids mutating the wired data, and assigning the sorted copy to this.data triggers a re-render.