React
Using ag-Grid with React: Rows

Sorting with the Grid API

Outline

We've seen how to sort the grid through the UI, so let's learn how to do it with the API by clicking a button.

We'll first define a function that defines a sort model and calls the grid API to set it:

// App.js
sortByAccountAndName = () => {
    const sort = [
      {
        colId: "accountName",
        sort: "asc",
      },
      {
        colId: "lastName",
        sort: "asc",
      },
    ];

    this.gridApi.setSortModel(sort);
  };

Note that we need to be sure to have a colId on our column definitions in order for this to work. We don't have one on the account name column, so we need to add it:

// App.js
// this.state column definitions
{
  headerName: "Acct Name",
  field: "accountName",
  colId: "accountName",
},

Finally, let's add our button above the AgGridReact component to call the sortByAccountAndName function:

// App.js
<button type="button" onClick={this.sortByAccountAndName}>
  Sort By Account and Last Name
</button>

There are all kinds of ways you can use the grid API to sort the grid programmatically, so be sure to read the docs on the sorting API to get more ideas.

 

I finished! On to the next chapter