react-data-table-component icon indicating copy to clipboard operation
react-data-table-component copied to clipboard

defaultSortFieldId and defaultSortAsc don't seem to function

Open mkabatek opened this issue 9 months ago • 3 comments

Hello,

I have some simple columns defined like this:

    const cols = [
      {
        id: "name",
        name: "Name",
        selector: (row: any) => row.name,
        sortable: true,
      },
      {
        id: "createdAt",
        name: "Created",
        selector: (row: any) => row.createdAt,
        sortable: true,
      },
      {
        name: "Actions",
        selector: (row: any) => row.actions,
        sortable: false,
      },
    ];

However for the life of me I cannot get the default sort to work when the table loads:

defaultSortFieldId={1}
defaultSortAsc={false}
defaultSortFieldId="name"
defaultSortAsc={false}

If I'm sorting by name which is my first column - setting defaultSortAsc={true} or defaultSortAsc={false} changes nothing. Same thing for date. I have tried using the unique ids, but it simply not working. I feel like this is a bug, however I'm unsure. Any help is appreciated.

mkabatek avatar Sep 14 '23 13:09 mkabatek

Did you figure this out after all?

AlexMoutonNoble avatar Nov 02 '23 20:11 AlexMoutonNoble

I am curious to know if you, @mkabatek, have found a solution, or if you still require assistance.

Allow me to share my findings on this matter:

  1. When the 'id' attribute is present in a column field, you should use the value of 'id' and cannot utilize the sequence number of the column.
  2. Conversely, when there is no 'id' attribute in the column field, you can employ the column sequence number.
  3. It's essential to note that you cannot use both simultaneously.

also "defaultSortAsc" is working as I checked it at my side. so may be if you update your version then it can resolve error.

I hope this clarification resolves any doubts you may have

Git-Codder avatar Nov 21 '23 15:11 Git-Codder

Yeh, just to add to this, I have had no issues with default sort, my rough implementation below:

const dateSort = (rowA, rowB) => {
    const a = new Date(rowA.id);
    const b = new Date(rowB.id);

    if (a > b) {
        return 1;
    }

    if (b > a) {
        return -1;
    }

    return 0;
    };

const columns = [
    {
        name: 'Date',
        selector: row => row.date,
        format: row => format(row.date, "MMM yy"),
        sortable: true,
        sortField: 'id',
        sortFunction: dateSort
    },
    {
        name: 'Amount',
        selector: row => row.amount,
    },
];

 <DataTable title="By Month" columns={columns} data={rows} progressPending={pending} 
         defaultSortFieldId={1} defaultSortAsc={false}
         progressComponent={<Spinner animation="border" role="status"  size="m"> </Spinner>} pagination /> 

piersdavidson avatar Jan 03 '24 06:01 piersdavidson