createArrayFilter
Description
The function takes filter value as an input and returns a filtered arrayIt uses the createFilter
helper inside.
Usage
createArrayFilter(
cfg: {
glue?: "and" | "or",
rules: {
field: string,
type?: "date" | "number" | "text" | "tuple",
predicate?: "month" | "year",
filter?: string,
value?: string | number | Date,
includes?: any[],
}[];
},
options?: { orNull?: boolean }
): ((data: any[]) => any[]) | null;
Parameters
cfg
- (required) filter settings:glue
- (optional) the logic for combining filtering rules:"and"
(default) - displays records that satisfy all rules"or"
- displays records that satisfy at least one rule
rules
- (required) an array of filtering rules. Each rule object can be an individual rule or a nested group (IFilterSet
). Each rule has the following properties:field
- (required) the ID of the field; must match the corresponding field in thefields
arraytype
- (optional) filter type:"text"
(default) |"number"
|"date"
|"tuple"
predicate
- (optional) date part extractor for date fields:"month"
|"year"
filter
- (optional) the filter operator available for this typevalue
- (optional) the value to filter byincludes
- (optional) an array of values to include
options
- (optional) behavior when no rules are set:orNull: true
- returnsnull
when there are no rulesorNull: false
(default) - returns the array
Returns
A function that takes an array and returns its filtered copy, or null
when options.orNull
is true
and there are no rules.
Example
This example demonstrates how to use createArrayFilter
to generate a function to filter a data array.
import { useState, useEffect } from "react";
import { getData } from "../data";
import { FilterBuilder, createArrayFilter } from "@svar-ui/react-filter";
export default function Example() {
const { value, fields, options, data } = getData();
const [filteredData, setFilteredData] = useState([]);
function applyFilter(value) {
const filter = createArrayFilter(value);
// filter may be null if options.orNull is true and there are no rules
if (filter) {
setFilteredData(filter(data));
} else {
setFilteredData(null);
}
}
// Apply initial filter on mount
useEffect(() => {
applyFilter(value);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
`<FilterBuilder
value={value}
fields={fields}
options={options}
onChange={({ value }) =>` applyFilter(value)}
/>
);
}