Miscellaneous
Refer to the TypeScript reference page for information about the types and interfaces referenced below.
A non-comprehensive list of exports from react-querybuilder
.
Utilities
transformQuery
function transformQuery(query: RuleGroupTypeAny, options: QueryTransformerOptions): any;
This function recursively steps through a query object (RuleGroupType
or RuleGroupTypeIC
), passing each RuleType
object to a provided ruleProcessor
function. Available options include:
ruleProcessor
: Custom processing for each rule.ruleGroupProcessor
: Custom processing for each rule group. Each group'srules
property will be retained and recursively processed regardless of any other mutations.propertyMap
: Keys in the rule or group objects that match keys in this object will be renamed to the corresponding value.combinatorMap
: Best explained with an example:{and: "&&", or: "||"}
would translate "and"/"or" combinators to "&&"/"||", respectively.operatorMap
: Convert operators that match the keys in this object to the corresponding values, e.g.{"=": "=="}
.deleteRemappedProperties
: Defaults totrue
; passfalse
to leave the remapped properties and the original properties in the resulting object.
See the test suite for example usage.
defaultValidator
function defaultValidator(query: RuleGroupTypeAny): {
[id: string]: { valid: boolean; reasons?: string[] };
};
Pass validator={defaultValidator}
to automatically validate groups (rules will be ignored). A group will be marked invalid if either of the following are true:
- The group has no child rules or groups (
query.rules.length === 0
) - The group has a missing/invalid
combinator
property and more than one child rule or group (rules.length >= 2
).
You can see an example of the default validator in action in the demo if you check the 'Use validation' option. Empty groups will have bold text on their "+ Rule" button and a description of the situation where the rules normally appear.
findPath
function findPath(path: Path, query: RuleGroupTypeAny): RuleType | RuleGroupTypeAny;
findPath
is a utility function for finding the rule or group within the query hierarchy that has a given path
. Useful in custom onAddRule
and onAddGroup
functions.
More extensive documentation on the path
property is here.
convertQuery
function convertQuery(query: RuleGroupType): RuleGroupTypeIC;
// OR
function convertQuery(query: RuleGroupTypeIC): RuleGroupType;
convertQuery
toggles a query between the conventional RuleGroupType
structure–with combinators at the group level–and the "independent combinators" structure RuleGroupTypeIC
–with combinators between every other rule/group.
convertToIC
and convertFromIC
do the same thing as convertQuery
, but only in the directions indicated by their respective names.
Query tools
Several methods are available to assist with programmatic manipulation of query objects. These methods are used by the <QueryBuilder />
component itself, so they are guaranteed to achieve the same result as a corresponding UI-based update. Each of these methods returns the modified query.
Check out the "External controls" Tips & Tricks page to see these methods used outside the context of the <QueryBuilder />
component.
add
(query: RuleGroupTypeAny, ruleOrGroup: RuleGroupTypeAny | RuleType, path: Path, options: AddOptions) => RuleGroupTypeAny
Adds a rule or group (and an independent combinator if necessary, to keep the query valid) to the group at the specified path
.
AddOptions
export interface AddOptions {
/**
* If the query extends `RuleGroupTypeIC` (i.e. the query has independent
* combinators), then the first combinator in this list will be inserted
* before the new rule/group if the parent group is not empty. This option
* is overridden by `combinatorPreceding`.
*/
combinators?: OptionList;
/**
* If the query extends `RuleGroupTypeIC` (i.e. the query has independent
* combinators), then this combinator will be inserted before the new rule/group
* if the parent group is not empty. This option will supersede `combinators`.
*/
combinatorPreceding?: string;
/**
* ID generator.
*/
idGenerator?: () => string;
}
Source: /packages/react-querybuilder/src/utils/queryTools.ts#L21-L39
remove
(query: RuleGroupTypeAny, path: Path) => RuleGroupTypeAny
Removes a rule or group (and the preceding independent combinator, if one exists).
update
(query: RuleGroupTypeAny, prop: string, value: any, path: Path, options: UpdateOptions) => RuleGroupTypeAny
Updates a property of a rule or group, or updates an independent combinator.
UpdateOptions
export interface UpdateOptions {
/**
* When updating the `field` of a rule, the rule's `operator`, `value`, and `valueSource`
* will be reset to their respective defaults. Defaults to `true`.
*/
resetOnFieldChange?: boolean;
/**
* When updating the `operator` of a rule, the rule's `value` and `valueSource`
* will be reset to their respective defaults. Defaults to `false`.
*/
resetOnOperatorChange?: boolean;
/**
* Determines the default operator name for a given field.
*/
getRuleDefaultOperator?: (field: string) => string;
/**
* Determines the valid value sources for a given field and operator.
*/
getValueSources?: (field: string, operator: string) => ValueSources;
/**
* Gets the default value for a given rule, in case the value needs to be reset.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
getRuleDefaultValue?: (rule: RuleType) => any;
}
Source: /packages/react-querybuilder/src/utils/queryTools.ts#L80-L104
move
(query: RuleGroupTypeAny, oldPath: Path, newPath: Path, options: MoveOptions) => RuleGroupTypeAny
Moves (or clones, with a new id
) a rule or group to a new location in the query tree.
MoveOptions
export interface MoveOptions {
/**
* When `true`, the source rule/group will not be removed from its original path.
*/
clone?: boolean;
/**
* If the query extends `RuleGroupTypeIC` (i.e. the query is using independent
* combinators), then the first combinator in this list will be inserted before
* the rule/group if necessary.
*/
combinators?: OptionList;
/**
* ID generator.
*/
idGenerator?: () => string;
}
Source: /packages/react-querybuilder/src/utils/queryTools.ts#L289-L304
insert
(query: RuleGroupTypeAny, ruleOrGroup: RuleGroupTypeAny | RuleType, path: Path, options: InsertOptions) => RuleGroupTypeAny
Inserts a rule or group (and an independent combinator if necessary, to keep the query valid) at the specified path
.
InsertOptions
export interface InsertOptions {
/**
* If the query extends `RuleGroupTypeIC` (i.e. the query has independent
* combinators), then the first combinator in this list will be inserted
* before the new rule/group if the parent group is not empty. This option
* is overridden by `combinatorPreceding`.
*/
combinators?: OptionList;
/**
* If the query extends `RuleGroupTypeIC` (i.e. the query has independent
* combinators), then this combinator will be inserted before the new rule/group
* if the parent group is not empty and the new rule/group is not the first in the
* group (`path.at(-1) > 0`). This option will supersede `combinators`.
*/
combinatorPreceding?: string;
/**
* If the query extends `RuleGroupTypeIC` (i.e. the query has independent
* combinators), then this combinator will be inserted after the new rule/group
* if the parent group is not empty and the new rule/group is the first in the
* group (`path.at(-1) === 0`). This option will supersede `combinators`.
*/
combinatorSucceeding?: string;
/**
* ID generator.
*
* @default generateID
*/
idGenerator?: () => string;
/**
* When `true`, the new rule/group will replace the rule/group at `path`.
*/
replace?: boolean;
}
Source: /packages/react-querybuilder/src/utils/queryTools.ts#L415-L447
Number parsing
HTML <input>
controls store values as strings (even for type="number"
), but your requirements may call for true numeric values. The parseNumbers
prop on the QueryBuilder
component and the formatQuery
function's parseNumbers
option can be used to convert values to numeric types from the UI or during export, respectively. Both configuration options have the same valid values (per the type below) and behave similarly.
boolean | "enhanced" | "enhanced-limited" | "native" | "native-limited" | "strict" | "strict-limited"
Tip: Try the
"strict-limited"
option first.
- The
"*-limited"
options are equivalent to their non-suffixed counterparts except that numeric parsing is only performed when the value editor'sinputType
is"number"
.- Being based on the
inputType
, the"*-limited"
suffix can only affectformatQuery
output when afields
array is also provided.
- Being based on the
true
,"strict"
, and"enhanced"
will retain the original value when numeric parsing fails."enhanced"
and"native"
can lead to information loss since any trailing invalid characters will be removed.true
and"strict"
determine numericity usingnumeric-quantity
withallowTrailingInvalid: false
. Values must be numeric in their entirety to be considered numeric, not just start with a number as withparseFloat
."enhanced"
usesnumeric-quantity
withallowTrailingInvalid: true
."native"
uses JavaScript's nativeparseFloat
method, which is similar to the "enhanced" algorithm in that it will strip trailing invalid characters, but it will returnNaN
for non-numeric values instead of the original value.
Examples
const query: RuleGroupType = {
combinator: 'and',
not: false,
rules: [
{ field: 'digits', operator: '=', value: '20' },
{ field: 'age', operator: 'between', value: '26, 52' },
{ field: 'lastName', operator: '=', value: 'Vai' },
],
};
// Default configuration - all values are strings:
formatQuery(query, { format: 'sql' });
// "(digits = '20' and age between '26' and '52' and lastName = 'Vai')"
// `parseNumbers: true` - numeric strings converted to actual numbers:
formatQuery(query, { format: 'sql', parseNumbers: true });
// "(digits = 20 and age between 26 and 52 and lastName = 'Vai')"
To avoid information loss, the true
and "strict*"
options are more strict about what qualifies as "numeric" than the standard parseFloat
function. To oversimplify a bit, parseFloat
works with any string that starts with a numeric sequence, ignoring the rest of the string beginning with the first non-numeric character. In contrast, when parseNumbers
is true
, formatQuery
will only convert a value
to a number
if it appears to be numeric in its entirety (after trimming whitespace).
Each of the following expressions evaluates to true
:
// Everything after the '3' is ignored by `parseFloat`
parseFloat('000123abcdef') === 123;
// `value` contains non-numeric characters, so remains as-is
formatQuery(
{ rules: [{ field: 'f', operator: '=', value: '000123abcdef' }] },
{ format: 'sql', parseNumbers: true }
) === "(f = '000123abcdef')";
// `value` is wholly numeric (after trimming whitespace) so it gets converted to a number
formatQuery(
{ rules: [{ field: 'f', operator: '=', value: ' 000123 ' }] },
{ format: 'sql', parseNumbers: true }
) === '(f = 123)';
Defaults
The default configuration objects are exported for convenience, including the following.
defaultCombinators
(seecombinators
prop)defaultOperators
(seeoperators
prop)defaultTranslations
(seetranslations
prop)defaultValueProcessor
and variants for non-SQL formats (see Export > Value processor)defaultFields
(seefields
prop)standardClassnames
(see CSS classes)
The default components are also exported:
ActionElement
- used for action buttons (to add rules, remove groups, etc.)DragHandle
- used for the drag handle on rules and group headersInlineCombinator
- used when eithershowCombinatorsBetweenRules
istrue
or the query is using independent combinators.NotToggle
- used for the "Invert this group" toggle switchRule
- the default rule componentRuleGroup
- the default rule group componentShiftActions
- used for the "shift up"/"shift down" buttons whenshowShiftActions
istrue
ValueEditor
- the defaultvalueEditor
componentValueSelector
- used for drop-down lists (combinator, field, and operator selectors)