Search code examples
reactjstypescriptag-grid

Sort on specific date column


I have the following AdGridReact

      <AgGridReact
        onGridReady={onGridReady}
        columnDefs={columnDefs}
        rowData={pipelineData}
        gridOptions={gridOptions}
        onCellClicked={onCellClicked}
      />

My columnDefs

  const columnDefs = [
    ...
    ...
    {
      headerName: 'My Date',
      field: 'myDate',
      unSortIcon: true,
      sortable: true,
      filter: true,
      resizable: true,
      suppressMenu: false,
      wrapText: true,
      autoHeight: true,
    }
  ];

The date format is "MM/DD/YYYY"

I'm trying to have the default sorting on the myDate column in ascending order.

I have tried multiple ways of achieving this, but none of them have worked.

One of the ways I tried is by using the setSortModel method

  const onGridReady = (params: any) => {
    setGridApi(params.api);
    setGridColumnApi(params.columnApi);
    params.api.sizeColumnsToFit();

    const sort = [
      {
        colId: "myDate",
        sort: "asc",
      },
    ];

    params.api.setSortModel(sort);
  };

But I get the following error: "params.api.setSortModel is not a function"

Any idea how I can get this to work?


Solution

  • If you want to sort by date, this is the way

    gridOptions.columnApi.applyColumnState({
      state: [{ colId: 'date', sort: 'asc' }],
      defaultState: { sort: null },
    });
    

    And do not forget to add a comparator for your date column otherwise it would be regarded as a string

    { 
      field: 'myDate',
      comparator: dateComparator
    },
    
    function dateComparator(date1, date2) {
      const date1Number = monthToComparableNumber(date1);
      const date2Number = monthToComparableNumber(date2);
    
      if (date1Number === null && date2Number === null) {
        return 0;
      }
      if (date1Number === null) {
        return -1;
      }
      if (date2Number === null) {
        return 1;
      }
    
      return date1Number - date2Number;
    }
    
    function monthToComparableNumber(date) {
      if (date === undefined || date === null || date.length !== 10) {
        return null;
      }
    
      const yearNumber = Number.parseInt(date.substring(6, 10));
      const monthNumber = Number.parseInt(date.substring(3, 5));
      const dayNumber = Number.parseInt(date.substring(0, 2));
    
      return yearNumber * 10000 + monthNumber * 100 + dayNumber;
    }
    

    Here's a working plunker: https://plnkr.co/edit/hn4Wg7ehOKXt7qpg?preview (Click on 'Date Ascending' button to see it in action)

    Further reading: https://www.ag-grid.com/javascript-data-grid/row-sorting/#sorting-api