createFilter
Description
The function takes filter settings as an input and creates a filterThe function creates a callback for filtering the array.
Usage
createFilter:(
value: {
glue: "and" | "or",
rules: {
field: string,
filter?: string,
value?: string | number | Date,
includes?: any[],
type?: "date"|"number"|"text"|"tuple",
}[]
},
options?: {
orNull?: boolean,
}
): (item: any) => boolean;
Parameters
value
- (required) filter settings:glue
- (required) the logic for combining filtering rules:- "and" (default) - displays records that correspond to all rules at once
- "or" - shows records that correspond to at least one of the rules
rules
- (required) an array of filtering rules. It can be an individual rule or a group of rules. Each rule object has the following parameters:field
- (required) the id of a field. It should be the same as the corresponding field id of thefields
property.filter
- (optional) the filter operator available for this typevalue
- (optional) the value in the fieldincludes
- (optional) an array of the included values (strings, numbers or dates).type
- (optional) filter type: "text" (default) | "number" | "date" | "tuple"
options
- (optional) it's applied when no rules are set; if set to true, null will be returned; if false (default), an array will be returned
Returns
It returns a function that is called for each element of the array - a ready-to-use callback for native Array.filter()
function.
Example
This example demonstrates how to use the createFilter
helper to apply filtering rules to an array of data.
import { useState, useEffect } from "react";
import { getData } from "../data";
import { FilterBuilder, createFilter } from "@svar-ui/react-filter";
export default function App() {
const { value, fields, options, data } = getData();
const [filteredData, setFilteredData] = useState([]);
function applyFilter(value) {
const filter = createFilter(value);
setFilteredData(data.filter(filter));
}
// Apply initial filter once on mount
useEffect(() => {
applyFilter(value);
}, []); // eslint-disable-line react-hooks/exhaustive-deps
return (
`<div>`
`<FilterBuilder
value={value}
fields={fields}
options={options}
onChange={({ value }) =>` applyFilter(value)}
/>
{/* Render filtered data as needed */}
</div>
);
}