Search code examples
javascriptreactjsag-grid

How to sort the columns values in ag-grid


I have displayed a set of data in the ag-grid, and the data is of complex type, i.e. values are displayed in the grid using a custom cell renderer.

I have given the option "sortable = true" but still columns are not getting sorted, even though I am not able to get value in the comparator() function.

Please help me with sorting the column values.

const sampleRowData = [
    {
        "field_name": "<some_value>",
        "field_value": "tgb34378eee847334894",
        "original_field_value": "tgb34378eee847334894",
        "_id": "1",
        "_img_id": "300",
    },
    {
        "field_name": "<some_value_1>",
        "field_value": "tgb34378eee847334895",
        "original_field_value": "tgb34378eee847334895",
        "_id": "2",
        "_img_id": "310",
    },
]

I want to sort the column values.


Solution

  • in ag-grid defaultColDef can be used for enabling sorting, like below

    import React, { useState, useMemo } from "react";
    import { render } from "react-dom";
    import { AgGridReact } from "ag-grid-react";
    
    import "ag-grid-community/styles/ag-grid.css";
    import "ag-grid-community/styles/ag-theme-alpine.css";
    
    const App = () => {
      const [rowData] = useState([
        { make: "tgb34378eee847334894", model: "Celica", price: 35000 },
        { make: "tgb34378eee847334895", model: "Mondeo", price: 32000 },
        { make: "Porsche", model: "Boxter", price: 72000 }
      ]);
    
      const [columnDefs] = useState([
        { field: "make" },
        { field: "model" },
        { field: "price" }
      ]);
      const defaultColDef = useMemo(() => {
        return {
          width: 270,
          sortable: true
        };
      }, []);
    
      return (
        <div className="ag-theme-alpine" style={{ height: 400, width: 600 }}>
          <AgGridReact
            defaultColDef={defaultColDef}
            rowData={rowData}
            columnDefs={columnDefs}
          ></AgGridReact>
        </div>
      );
    };
    
    export default App;
    

    You can see "sorting" is working here Edit Ag Grid React Hello World (forked)