0

I tried creating a lightning-datatable with custom data types, but unfortunately when trying to sort a column, it does not work. I have set the columns to sortable: true but still it does not work.

Component structure

c-main-component
    |---> c-custom-datatable

enter image description here

One thing i noticed though, it highlights the first cell when i tried to sort it.

enter image description here

5
  • Did you implement the sorting logic on your side? Only setting sortable=true on the columns definition is not enough, that only lets you "sort" on the column header but the you have to write your own sorting logic for it to work. The datatable doesn't know how you want your data to be sorted on its own. May 31, 2022 at 12:28
  • hi joacoiudica. yes i implemented it as well. i copied the sortBy and onHandleSort in the documentation
    – malacdon
    May 31, 2022 at 12:44
  • please, add all your code that is relevant to your problem on your question so I can see what you did. I can't give you an answer without any code May 31, 2022 at 13:04
  • Please add your sort code and also mention if Start date and end date are treated as String or date while sorting? May 31, 2022 at 13:09
  • Hi guys. thank you for your replies. Here is a playground link emulating the scenario: studio.webcomponents.dev/edit/cNzxx3E7cL6AQggK7dai The behavior is that when you click the sort, you can only do it two times then it stops sorting to either asc or desc
    – malacdon
    May 31, 2022 at 17:28

1 Answer 1

0

I found the issue. It is my fault. A good night sleep really helps.

I have a property declared as:

sortedBy = 'contractId';
sortedDirection = 'asc';

Im consuming it in the template as:

    <c-custom-datatable
        key-field="id"
        columns={columnsToPass}
        data={recordToShow}
        sorted-direction={sortedDirection}
        sorted-by={sortedBy}
        onsort={onHandleSort}
        hide-checkbox-column>
    </c-custom-datatable>

When I hit the sort I utilized the event handler:

onHandleSort(event) {
    const { fieldName: sortedBy, sortDirection } = event.detail;
    const cloneData = [...this.recordToShow];

    cloneData.sort(this.sortBy(sortedBy, sortDirection === 'asc' ? 1 : -1));
    this.recordToShow = cloneData;
    this.sortDirection = sortDirection;
    this.sortedBy = sortedBy;
}

My mistake was on the event handler

    this.sortDirection = sortDirection;

It should be:

    this.sortedDirection = sortDirection;
2
  • A piece of advice, whenever you can't find the reason as to why some code you wrote is not doing what you expect, ALWAYS check for sintax mistakes or spelling errors/confusions. This won't happen just once, so keep that in mind. Happy coding May 31, 2022 at 19:00
  • Thanks for the advice joacoiudica! appreciate it
    – malacdon
    May 31, 2022 at 19:08

You must log in to answer this question.

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