External filtering allows custom filtering logic to be mixed with the grid's inbuilt filtering.
This form of filtering is only compatible with the Client-Side Row Model, see Row Models for more details.
import { useFetchJson } from './useFetchJson';
"use client";
import React, { StrictMode, useCallback, useMemo, useState } from "react";
import { createRoot } from "react-dom/client";
import type { ColDef, IDateFilterParams, IRowNode } from "ag-grid-community";
import {
ClientSideRowModelModule,
DateFilterModule,
ExternalFilterModule,
NumberFilterModule,
enableDevValidations,
} from "ag-grid-community";
import {
ColumnMenuModule,
ColumnsToolPanelModule,
ContextMenuModule,
SetFilterModule,
} from "ag-grid-enterprise";
import { AgGridProvider, AgGridReact } from "ag-grid-react";
import type { IOlympicData } from "./interfaces";
import "./styles.css";
if (process.env.NODE_ENV !== "production") {
// Enable extended validations only for development
enableDevValidations();
}
const modules = [
ExternalFilterModule,
ClientSideRowModelModule,
ColumnsToolPanelModule,
ColumnMenuModule,
ContextMenuModule,
SetFilterModule,
NumberFilterModule,
DateFilterModule,
];
const asDate = (dateAsString: string): Date => {
const splitFields = dateAsString.split("/");
return new Date(
Number.parseInt(splitFields[2]),
Number.parseInt(splitFields[1]) - 1,
Number.parseInt(splitFields[0]),
);
};
const dateFilterParams: IDateFilterParams = {
comparator: (filterLocalDateAtMidnight: Date, cellValue: string) => {
const cellDate = asDate(cellValue);
if (filterLocalDateAtMidnight.getTime() === cellDate.getTime()) {
return 0;
}
if (cellDate < filterLocalDateAtMidnight) {
return -1;
}
if (cellDate > filterLocalDateAtMidnight) {
return 1;
}
return 0;
},
};
const defaultColDef: ColDef = { flex: 1, minWidth: 120, filter: true };
const columnDefs: ColDef<IOlympicData>[] = [
{ field: "athlete", minWidth: 180 },
{ field: "age", filter: "agNumberColumnFilter" },
{ field: "country" },
{ field: "year" },
{
field: "date",
filter: "agDateColumnFilter",
filterParams: dateFilterParams,
},
{ field: "total", filter: "agNumberColumnFilter" },
];
const GridExample = () => {
const [ageType, setAgeType] = useState("everyone");
const { data, loading } = useFetchJson<IOlympicData>(
"https://www.ag-grid.com/example-assets/olympic-winners.json",
);
// Both callbacks depend on ageType, so changing it hands the grid new references and filtering re-runs.
const isExternalFilterPresent = useCallback(
(): boolean => ageType !== "everyone",
[ageType],
);
const doesExternalFilterPass = useCallback(
(node: IRowNode<IOlympicData>): boolean => {
if (node.data) {
switch (ageType) {
case "below25":
return node.data.age < 25;
case "between25and50":
return node.data.age >= 25 && node.data.age <= 50;
case "above50":
return node.data.age > 50;
case "dateAfter2008":
return asDate(node.data.date) > new Date(2008, 0, 1);
default:
return true;
}
}
return true;
},
[ageType],
);
return (
<AgGridProvider modules={modules}>
<div className="test-container">
<div className="test-header">
<label>
<input
type="radio"
name="filter"
id="everyone"
defaultChecked
onChange={() => setAgeType("everyone")}
/>
Everyone
</label>
<label>
<input
type="radio"
name="filter"
id="below25"
onChange={() => setAgeType("below25")}
/>
Below 25
</label>
<label>
<input
type="radio"
name="filter"
id="between25and50"
onChange={() => setAgeType("between25and50")}
/>
Between 25 and 50
</label>
<label>
<input
type="radio"
name="filter"
id="above50"
onChange={() => setAgeType("above50")}
/>
Above 50
</label>
<label>
<input
type="radio"
name="filter"
id="dateAfter2008"
onChange={() => setAgeType("dateAfter2008")}
/>
After 01/01/2008
</label>
</div>
<div style={{ height: "100%" }}>
<AgGridReact<IOlympicData>
rowData={data}
loading={loading}
columnDefs={columnDefs}
defaultColDef={defaultColDef}
isExternalFilterPresent={isExternalFilterPresent}
doesExternalFilterPass={doesExternalFilterPass}
/>
</div>
</div>
</AgGridProvider>
);
};
const root = createRoot(document.getElementById("root")!);
root.render(
<StrictMode>
<GridExample />
</StrictMode>,
);
.test-container {
height: 100%;
display: flex;
flex-direction: column;
}
.test-header {
font-family: Verdana, Geneva, Tahoma, sans-serif;
font-size: 13px;
margin-bottom: 10px;
display: flex;
justify-content: space-around;
border: 1px solid grey;
padding: 10px;
border-radius: 5px;
}
export interface IOlympicData {
athlete: string,
age: number,
country: string,
year: number,
date: string,
sport: string,
gold: number,
silver: number,
bronze: number,
total: number
} import { useState, useEffect } from 'react';
/**
* Fetch example Json data
* Not recommended for production use!
*/
export const useFetchJson = <T,>(url:string, limit?: number) => {
const [data, setData] = useState<T[]>();
const [loading, setLoading] = useState(true);
useEffect(() => {
// StrictMode runs this effect twice: drop the superseded run's response rather than applying both.
let cancelled = false;
const fetchData = async () => {
setLoading(true);
// Note error handling is omitted here for brevity
const response = await fetch(url);
const json = await response.json();
const data = limit ? json.slice(0, limit) : json;
if (cancelled) {
return;
}
setData(data);
setLoading(false);
};
fetchData();
return () => {
cancelled = true;
};
}, [url, limit]);
return { data, loading };
}; Implementing External Filtering Copy Link
The example above shows external filters in action. Two methods on gridOptions are required to be implemented: isExternalFilterPresent and doesExternalFilterPass.
Grid calls this method to know if an external filter is present.
Called exactly once every time the grid senses a filter change.
Should return true if external filtering is active, otherwise false.
If true, doesExternalFilterPass is called while filtering, otherwise it is not called.
Supplying a new function reference re-runs external filtering. |
Called once for each row node in the grid.
Should return true if external filter passes, otherwise false.
If false, the node is excluded from the final set.
Only runs if isExternalFilterPresent returns true.
Supplying a new function reference re-runs external filtering. |
Re-running the External Filter Copy Link
The filter state is held outside the grid, so the grid has to be told when that state has changed. Pick one of the following approaches:
- Calling onFilterChanged - the callback references are kept stable and the filter is re-run only when the API is called.
- Supplying New Callbacks - a new callback reference is handed to the grid and the filter is re-run automatically.
Calling onFilterChanged Copy Link
After the filter state has changed call api.onFilterChanged() to ask the grid to run filtering again.
Informs the grid that a filter has changed. This is typically called after a filter change through one of the filter APIs.
source: The source of the filter change event. If not specified defaults to 'api'. |
// Filter state updated now re-run filtering
api.onFilterChanged();Ensure the callbacks have stable references to avoid triggering filtering excessively.
Avoid passing an inline lambda as it will provide a new function on every render, so the grid re-filters every time the component renders:
// re-filters on every render
<AgGridReact doesExternalFilterPass={(node) => node.data.age > minAge} /> Supplying New Callbacks Copy Link
isExternalFilterPresent and doesExternalFilterPass are reactive grid properties, so replacing either one with a new function re-runs filtering automatically.
Where the filter value is held in state ensure this is included in the callback dependency array so that the grid receives a new reference each time it changes to trigger filtering.
const [ageType, setAgeType] = useState('everyone');
const isExternalFilterPresent = useCallback(() => ageType !== 'everyone', [ageType]);
const doesExternalFilterPass = useCallback((node) => ageType === 'everyone' || node.data.age > 50, [ageType]);The example on this page takes the second path: ageType is component state, and both callbacks list it as a dependency.