jbetancur / react-data-table-component

A responsive table library with built-in sorting, pagination, selection, expandable rows, and customizable styling.
https://react-data-table-component.netlify.app
Apache License 2.0
2.04k stars 411 forks source link

defaultSortFieldId and defaultSortAsc don't seem to function #1164

Open mkabatek opened 1 year ago

mkabatek commented 1 year ago

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.

AlexMoutonNoble commented 10 months ago

Did you figure this out after all?

Git-Codder commented 9 months ago

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

piersdavidson commented 8 months ago

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 />