I am using the ag-grid
package to display a grid/table in my react application. And, I have a custom filter-search requirement.
I want to type-in the values separated by some delimiter in the mini text filter field bar provided by the package itself and want all the corresponding options appear in the filtering list.
The image shown below is exactly what I need, only this time I want ‘id1’, ‘id2’ and ‘id3’ values to appear in the box instead of ‘No Matches.’.
I also went to through the official documentation and there are plenty of options to customize our grid filter feature in many different ways, but nothing that can match my need.
I am thinking if I could get a hold of the event that gets triggered when one types-in some value in the field and then render the options based on that value, to sort of customize it accordingly. But I am not sure if this is even possible, and if not, then is there any alternative.
Thanks in Advance!
How about creating your own custom filter component? Create your own custom filter component which filter the table data using the values split by the semi-colon:
export default ({ model, onModelChange, getValue }: CustomFilterProps) => {
const refInput = useRef<HTMLInputElement>(null);
const doesFilterPass = useCallback(
(params: IDoesFilterPassParams) => {
const { node } = params;
const filterText: string = model;
const value: string = getValue(node).toString().toLowerCase();
if (!filterText) return true;
// Split the filterText by semicolons and trim whitespace
const filterValues = filterText
.toLowerCase()
.split(';')
.map((filterWord) => filterWord.trim());
// Check if the row value matches any of the filter values
return filterValues.some((filterWord) => value === filterWord);
},
[model, getValue]
);
const afterGuiAttached = useCallback((params?: IAfterGuiAttachedParams) => {
if (!params || !params.suppressFocus) {
// Focus the input element for keyboard navigation.
refInput.current?.focus();
}
}, []);
// Register filter handlers with the grid
useGridFilter({
doesFilterPass,
afterGuiAttached,
});
return (
<div className="person-filter">
<div>Custom Filter</div>
<div>
<input
ref={refInput}
type="text"
value={model || ''}
onChange={({ target: { value } }) => onModelChange(value === '' ? null : value)}
placeholder="Enter IDs separated by semicolons..."
/>
</div>
<div>
This filter matches exact values separated by semicolons, e.g. "id1;id2;id3".
</div>
</div>
);
};
Demo.