0

I have a component with a Lightning-data-table but I can't get the vertical scrollbar to show up and although, when I add 'sortable' to a column, the arrow appears but nothing happens when I click the column. It's probably a simple omission somewhere but every example I look at it just seems to have the scrollbar already there, without having to add anything to the table definition. What am I missing?

const columns = [
{ label: "Name", fieldName: "Name", sortable: true },
{
 label: "Membership",
 fieldName: "Membership__c",
 sortable: true
},
{
 label: "Status",
 fieldName: "Status__c",
 sortable: true
}
];

The table:

 <div class="slds-form-element__control slds-m-around_medium">
    <lightning-datatable
      key-field="Id"
      data={data}
      columns={columns}
      onrowselection={getSelectedRecord}
      show-row-number-column
    >
    </lightning-datatable>
 </div>

1 Answer 1

1

To be able to get the scroll bar, set the height to the parent div.


Sorting

You need to add sorted-by value to your datatable.

<div class="slds-form-element__control slds-m-around_medium">
    <lightning-datatable
      key-field="Id"
      data={data}
      sorted-by={sortedBy}
      onsort={updateColumnSorting}
      columns={columns}
      onrowselection={getSelectedRecord}
      show-row-number-column
    >
    </lightning-datatable>
 </div>

Also, add a method to handle onsort.

sortedBy;
// ...
updateColumnSorting(event) {
    var fieldName = event.detail.fieldName;
    var sortDirection = event.detail.sortDirection;
    // assign the latest attribute with the sorted column fieldName and sorted direction
    this.sortedBy = fieldName;
    this.sortedDirection = sortDirection;
    this.data = this.sortData(fieldName, sortDirection);
}

lastly, define the sortData.

sortData(fieldname, direction) {
    let parseData = JSON.parse(JSON.stringify(this.data));
    // Return the value stored in the field
    let keyValue = (a) => {
        return a[fieldname];
    };
    // cheking reverse direction
    let isReverse = direction === ‘asc’ ? 1 : -1;
    // sorting data
    parseData.sort((x, y) => {
        x = keyValue(x) ? keyValue(x) : ‘’; // handling null values
        y = keyValue(y) ? keyValue(y) : ‘’;
        // sorting values based on direction
        return isReverse * ((x > y)—(y > x));
    });
    this.data = parseData;
}

References
Lightning Web Component Datatable
Lightning Datatable Sorting in Lightning Web Components

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .