Using ag-Grid with React: Filters

Set Filters


In this video, we talk about a really cool feature called set filters. Set filters are really similar to what you know as filters in Microsoft Excel, where you can filter data based on values in a column.

Set filters are part of ag-Grid Enterprise, but don't worry; you can test drive all of the enterprise features without a license. You just can't use them in production.

We first need to install ag-grid-enterprise:

npm install ag-grid-enterprise@~22.1.0 --save

We're keeping all of the ag-Grid versions at 22.x in this series of tutorials. Go ahead and update the ^ to a ~ in your package.json to lock this version in to everything but patch updates:

// package.json
"dependencies": {
  "ag-grid-enterprise": "~22.1.1",

(Your precise version number may look slightly different.)

Once the enterprise package installs, import it at the top of App.js:

// src/App.js
import 'ag-grid-enterprise'

Now, in the account name column definition, add the set filter:

// src/App.js
   headerName: "Acct Name",
   field: "accountName",
   filter: "agSetColumnFilter"

If you run npm start and navigate to localhost:3000, you'll see some UI changes due to the enterprise package. When you open the filter for the account name column, you'll now have the ability to select and deselect values in order to filter them out. Try deselecting "Checking Account" and seeing what happens.

It'd be cool if we could do more than this, and it turns out we have the same power of the filter API for set filters. Let's create a button that:

  • Filters to only checking and savings accounts, and
  • Sorts the grid by last name ascending.

First, create the button next to our "Mo Filter" button:

<button type="button" onClick={this.checkingAndSavings}>
  Checking and Savings

Then, write the checkingAndSavings function:

checkingAndSavings = () => {
   const accountNameFilter = this.gridApi.getFilterInstance("accountName");
   accountNameFilter.selectValue("Checking Account");
   accountNameFilter.selectValue("Savings Account");
   this.gridApi.setSortModel([{ colId: "lastName", sort: "asc" }]);

You'll notice a similar pattern to the moFilter function: we get the instance of the filter, set its model, and notify ag-Grid of the changes.

If you run npm start and navigate to localhost:3000, you're now able to click "Checking and Savings" to see only checking and savings accounts sorted by last name ascending. Wow!

That wraps up this tutorial on Filters. Great work! The next tutorial is on Rows — see you there!