### Install react-querybuilder with Bun
Source: https://react-querybuilder.js.org/docs/intro
Use this command to install the library via Bun.
```bash
bun add react-querybuilder
```
--------------------------------
### Basic React Query Builder Setup with ESM
Source: https://react-querybuilder.js.org/docs/buildless
This example shows how to set up and render a basic QueryBuilder component using ESM imports in an HTML file. Ensure Babel is included for JSX parsing in script tags.
```html
React Query Builder ESM
```
--------------------------------
### Install react-querybuilder with npm
Source: https://react-querybuilder.js.org/docs/intro
Use this command to install the library via npm.
```bash
npm i react-querybuilder
```
--------------------------------
### Install react-querybuilder with Yarn
Source: https://react-querybuilder.js.org/docs/intro
Use this command to install the library via Yarn.
```bash
yarn add react-querybuilder
```
--------------------------------
### Install react-querybuilder with pnpm
Source: https://react-querybuilder.js.org/docs/intro
Use this command to install the library via pnpm.
```bash
pnpm add react-querybuilder
```
--------------------------------
### Install React Query Builder and Rules Engine (npm)
Source: https://react-querybuilder.js.org/docs/rules-engine
Install the necessary packages using npm.
```bash
npm install react-querybuilder @react-querybuilder/rules-engine
```
--------------------------------
### Mock API Loader Setup
Source: https://react-querybuilder.js.org/docs/tips/async-option-lists
Provides a mock implementation for `loadOptionList` and `getCacheKey` functions to simulate asynchronous data loading for auto-complete examples. Includes a predefined list of words for filtering.
```typescript
// prettier-ignore
const words = [ "React", "Angular", "Vue", "Svelte", "Next.js", "Nuxt.js", "Gatsby", "TypeScript", "JavaScript", "Python", "Java", "C#", "Go", "Rust", "Node.js", "Express", "Fastify", "Koa", "Hapi", "NestJS", "MongoDB", "PostgreSQL", "MySQL", "Redis", "SQLite", "Docker", "Kubernetes", "AWS", "Azure", "GCP"];
const loadOptionList = async (value: string | undefined): Promise => {
await new Promise(resolve => setTimeout(resolve, 500));
if (value && value.length > 0) {
return words.filter(word => word.toLowerCase().includes(value.toLowerCase()));
}
return [];
};
const getCacheKey = ({ value }: ValueEditorProps) => value;
```
--------------------------------
### Install React Query Builder and Rules Engine (pnpm)
Source: https://react-querybuilder.js.org/docs/rules-engine
Install the necessary packages using pnpm.
```bash
pnpm add react-querybuilder @react-querybuilder/rules-engine
```
--------------------------------
### Install react-querybuilder with react-dnd dependencies (bun)
Source: https://react-querybuilder.js.org/docs/dnd
Install the necessary packages for react-querybuilder and its react-dnd integration using bun.
```bash
bun add react-querybuilder @react-querybuilder/dnd react-dnd react-dnd-html5-backend react-dnd-touch-backend
```
--------------------------------
### Install DnD-Kit Dependencies (Bun)
Source: https://react-querybuilder.js.org/docs/dnd
Install the necessary packages for React Query Builder, its drag-and-drop module, and the DnD-Kit library using Bun.
```bash
bun add react-querybuilder @react-querybuilder/dnd @dnd-kit/core
```
--------------------------------
### Define Example Query
Source: https://react-querybuilder.js.org/docs/utils/export
This is an example query object used throughout the documentation for demonstrating export functionality.
```typescript
const query: RuleGroupType = {
id: 'root',
combinator: 'and',
not: false,
rules: [
{
id: 'rule1',
field: 'firstName',
operator: '=',
value: 'Steve',
},
{
id: 'rule2',
field: 'lastName',
operator: '=',
value: 'Vai',
},
],
};
```
--------------------------------
### Install Pragmatic Drag and Drop Dependencies (Bun)
Source: https://react-querybuilder.js.org/docs/dnd
Install the necessary packages for React Query Builder, its drag-and-drop module, and the Pragmatic Drag and Drop library using Bun.
```bash
bun add react-querybuilder @react-querybuilder/dnd @atlaskit/pragmatic-drag-and-drop
```
--------------------------------
### Install React Query Builder with DnD
Source: https://react-querybuilder.js.org/docs/components/querybuilder
Install the necessary packages for React Query Builder and its drag-and-drop functionality using npm, yarn, or pnpm.
```bash
npm install @react-querybuilder/dnd
# or
yarn add @react-querybuilder/dnd
# or
bun add @react-querybuilder/dnd
```
--------------------------------
### Install DnD-Kit Dependencies (npm)
Source: https://react-querybuilder.js.org/docs/dnd
Install the necessary packages for React Query Builder, its drag-and-drop module, and the DnD-Kit library using npm.
```bash
npm i react-querybuilder @react-querybuilder/dnd @dnd-kit/core
```
--------------------------------
### Install react-querybuilder with react-dnd dependencies (npm)
Source: https://react-querybuilder.js.org/docs/dnd
Install the necessary packages for react-querybuilder and its react-dnd integration using npm.
```bash
npm i react-querybuilder @react-querybuilder/dnd react-dnd react-dnd-html5-backend react-dnd-touch-backend
```
--------------------------------
### Basic Query Builder Setup (TypeScript)
Source: https://react-querybuilder.js.org/docs/intro
Renders a basic QueryBuilder component. Import the official stylesheet for styling.
```typescript
import { QueryBuilder } from 'react-querybuilder';
import 'react-querybuilder/dist/query-builder.css';
export default () => ;
```
--------------------------------
### Install DnD-Kit Dependencies (Yarn)
Source: https://react-querybuilder.js.org/docs/dnd
Install the necessary packages for React Query Builder, its drag-and-drop module, and the DnD-Kit library using Yarn.
```bash
yarn add react-querybuilder @react-querybuilder/dnd @dnd-kit/core
```
--------------------------------
### Install react-querybuilder with react-dnd dependencies (yarn)
Source: https://react-querybuilder.js.org/docs/dnd
Install the necessary packages for react-querybuilder and its react-dnd integration using yarn.
```bash
yarn add react-querybuilder @react-querybuilder/dnd react-dnd react-dnd-html5-backend react-dnd-touch-backend
```
--------------------------------
### Install react-querybuilder with react-dnd dependencies (pnpm)
Source: https://react-querybuilder.js.org/docs/dnd
Install the necessary packages for react-querybuilder and its react-dnd integration using pnpm.
```bash
pnpm add react-querybuilder @react-querybuilder/dnd react-dnd react-dnd-html5-backend react-dnd-touch-backend
```
--------------------------------
### Install Pragmatic Drag and Drop Dependencies (npm)
Source: https://react-querybuilder.js.org/docs/dnd
Install the necessary packages for React Query Builder, its drag-and-drop module, and the Pragmatic Drag and Drop library using npm.
```bash
npm i react-querybuilder @react-querybuilder/dnd @atlaskit/pragmatic-drag-and-drop
```
--------------------------------
### Install Pragmatic Drag and Drop Dependencies (Yarn)
Source: https://react-querybuilder.js.org/docs/dnd
Install the necessary packages for React Query Builder, its drag-and-drop module, and the Pragmatic Drag and Drop library using Yarn.
```bash
yarn add react-querybuilder @react-querybuilder/dnd @atlaskit/pragmatic-drag-and-drop
```
--------------------------------
### Install Pragmatic Drag and Drop Dependencies (pnpm)
Source: https://react-querybuilder.js.org/docs/dnd
Install the necessary packages for React Query Builder, its drag-and-drop module, and the Pragmatic Drag and Drop library using pnpm.
```bash
pnpm add react-querybuilder @react-querybuilder/dnd @atlaskit/pragmatic-drag-and-drop
```
--------------------------------
### Install DnD-Kit Dependencies (pnpm)
Source: https://react-querybuilder.js.org/docs/dnd
Install the necessary packages for React Query Builder, its drag-and-drop module, and the DnD-Kit library using pnpm.
```bash
pnpm add react-querybuilder @react-querybuilder/dnd @dnd-kit/core
```
--------------------------------
### Install Dependencies for Drag and Drop
Source: https://react-querybuilder.js.org/docs/api/querybuilder
Installs the necessary packages for enabling drag-and-drop reordering functionality in React Query Builder.
```bash
npm i react-querybuilder @react-querybuilder/dnd react-dnd react-dnd-html5-backend
# OR yarn add / pnpm add / bun add
```
--------------------------------
### Install React Query Builder DnD dependencies
Source: https://react-querybuilder.js.org/docs/components/querybuilder
Installs the necessary packages for enabling drag and drop functionality in React Query Builder.
```bash
npm i react-querybuilder @react-querybuilder/dnd react-dnd react-dnd-html5-backend
```
--------------------------------
### Define a sample query object
Source: https://react-querybuilder.js.org/docs/api/export
This is an example of a RuleGroupType query object used in subsequent examples.
```typescript
const query: RuleGroupType = {
id: 'root',
combinator: 'and',
not: false,
rules: [
{
id: 'rule1',
field: 'firstName',
operator: '=',
value: 'Steve',
},
{
id: 'rule2',
field: 'lastName',
operator: '=',
value: 'Vai',
},
],
};
```
--------------------------------
### Example Diagnostics Output
Source: https://react-querybuilder.js.org/docs/utils/export
This is an example of the diagnostics output object, showing the annotated query tree, flat diagnostics array, statistics, and field summary.
```json
{
"query": {
"combinator": "and",
"valid": false,
"path": [],
"level": 0,
"rules": [
{
"field": "firstName",
"operator": "=",
"value": "",
"valid": false,
"reasons": ["Value is required"],
"path": [0],
"level": 1
},
{
"field": "age",
"operator": ">",
"value": 26,
"valid": true,
"path": [1],
"level": 1
}
]
},
"diagnostics": [
{
"id": "r-1",
"path": [0],
"code": "CUSTOM_VALIDATOR",
"message": "Invalid: Value is required",
"source": "field-validator"
}
],
"stats": {
"totalRules": 2,
"totalGroups": 1,
"validRules": 1,
"invalidRules": 1,
"validGroups": 0,
"invalidGroups": 1
},
"fieldSummary": {
"firstName": { "ruleCount": 1, "invalidCount": 1 },
"age": { "ruleCount": 1, "invalidCount": 0 }
}
}
```
--------------------------------
### SQL Example for Field Comparison
Source: https://react-querybuilder.js.org/docs/api/valueeditor
Illustrates a SQL WHERE clause comparing two fields, `lastName` and `firstName`, using LIKE and concatenation.
```sql
SELECT *
FROM users
WHERE lastName LIKE firstName || '%';
```
--------------------------------
### Override CSS Variables Example
Source: https://react-querybuilder.js.org/docs/styling/overview
Example of overriding default CSS variables to customize spacing and background color.
```css
@import 'react-querybuilder/dist/query-builder.css';
:root {
--rqb-spacing: 0.8rem; /* a little roomier than the default 0.5rem */
--rqb-background-color: #ccc3; /* gray, semi-transparent background */
}
```
--------------------------------
### useQueryBuilderSchema
Source: https://react-querybuilder.js.org/docs/utils/hooks
Returns elements for rendering wrapper and root RuleGroup based on props and setup.
```APIDOC
## `useQueryBuilderSchema`
### Description
Called by the internal component rendered by `QueryBuilder`. Returns everything needed to render a wrapper element (e.g., `
`) and the root `RuleGroup` element based on the provided props and the result from `useQueryBuilderSetup`.
### Usage Note
This hook is unlikely to be necessary unless you're reimplementing the entire `QueryBuilder` component structure. It must be called from a descendant component of `QueryBuilderStateProvider`.
### Parameters
#### Request Body
- **props** (QueryBuilderProps) - Required - Properties for the QueryBuilder.
- **setup** (ReturnType) - Required - The result from `useQueryBuilderSetup`.
### Returns
- **actions** (QueryActions) - Actions available for the query builder.
- **rootGroup** (RuleGroupTypeAny) - The root rule group element.
- **rootGroupDisabled** (RuleGroupTypeAny) - The disabled state of the root rule group.
- **queryDisabled** (boolean) - Indicates if the entire query is disabled.
- **rqbContext** (ReturnType) - The merged context values.
- **schema** (Schema) - The schema configuration for the query builder.
- **translations** (TranslationsFull) - Full translation objects.
- **wrapperClassName** (string) - CSS class name for the wrapper element.
- **dndEnabledAttr** ('enabled' | 'disabled') - Attribute indicating if drag and drop is enabled.
- **inlineCombinatorsAttr** ('enabled' | 'disabled') - Attribute indicating if inline combinators are enabled.
- **combinatorPropObject** (Pick) - Object containing the combinator property for a rule group.
```
--------------------------------
### Import from react-querybuilder/debug (Deprecated)
Source: https://react-querybuilder.js.org/docs/migrate
Example of importing from the deprecated `/debug` entry point of react-querybuilder. This may be removed in future versions.
```javascript
import from "react-querybuilder/debug";
```
--------------------------------
### Default Parameterized Output
Source: https://react-querybuilder.js.org/docs/tips/custom-bind-variables
This is an example of the output from formatQuery(query, "parameterized") before custom placeholder replacement.
```json
{
"sql": "(firstName = ? and lastName = ?)",
"params": ["Steve", "Vai"]
}
```
--------------------------------
### SQL Parsing Output Example
Source: https://react-querybuilder.js.org/docs/api/import
Illustrates the `RuleGroupType` output generated by the `parseSQL` function when parsing a SQL WHERE clause.
```json
{
"combinator": "and",
"rules": [
{
"field": "firstName",
"operator": "=",
"value": "Steve"
},
{
"field": "lastName",
"operator": "=",
"value": "Vai"
}
]
}
```
--------------------------------
### Real-time SQL Generation with formatQuery
Source: https://react-querybuilder.js.org/docs/intro
Use the `formatQuery` function to convert query objects to SQL. This example shows how to integrate it into a React component for dynamic updates.
```javascript
import { useState } from 'react';
import { Field, formatQuery, QueryBuilder, RuleGroupType } from 'react-querybuilder';
import 'react-querybuilder/dist/query-builder.css';
const fields: Field[] = [
{ name: 'firstName', label: 'First Name' },
{ name: 'lastName', label: 'Last Name' },
];
export default () => {
const [query, setQuery] = useState({
combinator: 'and',
rules: [
{ field: 'firstName', operator: 'beginsWith', value: 'Stev' },
{ field: 'lastName', operator: 'in', value: 'Vai,Vaughan' },
],
});
return (
<>
SQL as result of formatQuery(query, 'sql'):
{formatQuery(query, 'sql')}
>
);
};
```
--------------------------------
### Example of listsAsArrays behavior
Source: https://react-querybuilder.js.org/docs/components/querybuilder
Demonstrates how the `listsAsArrays` prop changes the format of rule values for list-based editors and specific operators.
```json
{
"field": "f1",
"operator": "between",
"value": "f2,f3",
"valueSource": "field"
}
```
```json
{
"field": "f1",
"operator": "between",
"value": ["f2", "f3"],
"valueSource": "field"
}
```
--------------------------------
### MongoDB Parsing Usage Examples
Source: https://react-querybuilder.js.org/docs/api/import
Demonstrates how to use the `parseMongoDB` function with either a JSON string or a JavaScript object representing a MongoDB query.
```javascript
parseMongoDB(`{ "firstName": "Steve", "lastName": { $eq: "Vai" } }`);
// OR
parseMongoDB({ firstName: 'Steve', lastName: { $eq: 'Vai' } });
```
--------------------------------
### Basic RulesEngineBuilder Usage
Source: https://react-querybuilder.js.org/docs/rules-engine
Render the `RulesEngineBuilder` component for basic rule set creation. No specific imports are needed beyond the component itself for this basic setup.
```jsx
import { RulesEngineBuilder } from '@react-querybuilder/rules-engine';
function App() {
return ;
}
```
--------------------------------
### Valid RuleGroupTypeIC Example 1
Source: https://react-querybuilder.js.org/docs/typescript
Shows a valid RuleGroupTypeIC structure by removing the leading string combinator, resulting in an array starting with a rule and having an odd length.
```typescript
const ruleGroupValid1: RuleGroupTypeIC = {
rules: [{ field: 'firstName', operator: '=', value: 'Steve' }],
};
```
--------------------------------
### Override SCSS Variables Example
Source: https://react-querybuilder.js.org/docs/styling/overview
Example of overriding default SCSS variables to customize spacing and background color.
```scss
@use 'react-querybuilder/dist/query-builder' with (
$rqb-spacing: 0.8rem, /* a little roomier than the default 0.5rem */
$rqb-background-color: #ccc3 /* gray, semi-transparent background */
);
```
--------------------------------
### SQL Parsing Usage Examples
Source: https://react-querybuilder.js.org/docs/api/import
Demonstrates various ways to use the `parseSQL` function, including parsing a full SELECT statement, and using named or anonymous bind variables with the `params` and `paramPrefix` options.
```javascript
parseSQL(`SELECT * FROM t WHERE firstName = 'Steve' AND lastName = 'Vai'`);
parseSQL(`SELECT * FROM t WHERE firstName = ? AND lastName = ?`, {
params: ['Steve', 'Vai'],
});
parseSQL(`SELECT * FROM t WHERE firstName = :p1 AND lastName = :p2`, {
params: { p1: 'Steve', p2: 'Vai' },
});
parseSQL(`SELECT * FROM t WHERE firstName = $p1 AND lastName = $p2`, {
params: { p1: 'Steve', p2: 'Vai' },
paramPrefix: '$',
});
```
--------------------------------
### Override SCSS Variables Example
Source: https://react-querybuilder.js.org/docs/tips/styling
Example of overriding default SCSS variables using the `with` clause to customize spacing and background color.
```scss
@use 'react-querybuilder/dist/query-builder' with (
$rqb-spacing: 0.8rem,
$rqb-background-color: #ccc3 /* gray, semi-transparent background */
);
```
--------------------------------
### SQL Parsing Usage Examples
Source: https://react-querybuilder.js.org/docs/utils/import
Demonstrates various ways to use the parseSQL function, including handling different SQL SELECT statement formats and using parameter binding with options.
```javascript
parseSQL(`SELECT * FROM t WHERE firstName = 'Steve' AND lastName = 'Vai'`);
parseSQL(`SELECT * FROM t WHERE firstName = ? AND lastName = ?`, {
params: ['Steve', 'Vai'],
});
parseSQL(`SELECT * FROM t WHERE firstName = :p1 AND lastName = :p2`, {
params: { p1: 'Steve', p2: 'Vai' },
});
parseSQL(`SELECT * FROM t WHERE firstName = $p1 AND lastName = $p2`, {
params: { p1: 'Steve', p2: 'Vai' },
paramPrefix: '$',
});
```
--------------------------------
### Configure DnD-Kit with QueryBuilderDnD
Source: https://react-querybuilder.js.org/docs/dnd
Set up the QueryBuilderDnD context provider with the DnD-Kit adapter. This enables drag-and-drop functionality and automatically applies ARIA attributes for accessibility.
```jsx
import { QueryBuilderDnD } from '@react-querybuilder/dnd';
import { createDndKitAdapter } from '@react-querybuilder/dnd/dnd-kit';
import * as DndKit from '@dnd-kit/core';
import { QueryBuilder } from 'react-querybuilder';
const dndKitAdapter = createDndKitAdapter(DndKit);
const App = () => (
);
```
--------------------------------
### Use Query Builder Setup Hook
Source: https://react-querybuilder.js.org/docs/utils/hooks
Internal hook called by `QueryBuilder` to merge props and context, generate actions, and prepare initial state. It's generally not needed unless reimplementing the entire `QueryBuilder` component.
```typescript
function useQueryBuilderSetup(props: QueryBuilderProps): {
qbId: qbId.current;
rqbContext: ReturnType;
fields: OptionList;
fieldMap: Record;
combinators: OptionList;
getOperatorsMain: (field: string) => OptionList;
getRuleDefaultOperator: (field: string) => string;
getValueEditorTypeMain: (field: string, operator: string) => ValueEditorType;
getValueSourcesMain: (field: string, operator: string) => ValueSources;
getValuesMain: (field: string, operator: string) => OptionList;
getRuleDefaultValue: (rule: RuleType) => any;
getInputTypeMain: (field: string, operator: string) => string;
createRule: () => RuleType;
createRuleGroup: () => RuleGroupTypeAny;
};
```
--------------------------------
### Create and use the react-dnd adapter
Source: https://react-querybuilder.js.org/docs/dnd
Create a react-dnd adapter by combining exports from react-dnd and its backends, then use it with QueryBuilderDnD.
```jsx
import { QueryBuilderDnD } from '@react-querybuilder/dnd';
import { createReactDnDAdapter } from '@react-querybuilder/dnd/react-dnd';
import * as ReactDnD from 'react-dnd';
import * as ReactDndHtml5Backend from 'react-dnd-html5-backend';
import * as ReactDndTouchBackend from 'react-dnd-touch-backend';
import { QueryBuilder } from 'react-querybuilder';
const reactDnDAdapter = createReactDnDAdapter({
...ReactDnD,
...ReactDndHtml5Backend,
...ReactDndTouchBackend,
});
const App = () => (
);
```
--------------------------------
### Override CSS Variables Example
Source: https://react-querybuilder.js.org/docs/tips/styling
Example of overriding default CSS variables to customize spacing and background color. Ensure the default stylesheet is imported first.
```css
@import 'react-querybuilder/dist/query-builder.css';
:root {
--rqb-spacing: 0.8rem; /* a little roomier than the default 0.5rem */
--rqb-background-color: #ccc3; /* gray, semi-transparent background */
}
```
--------------------------------
### Bad Cache Key Design Example
Source: https://react-querybuilder.js.org/docs/tips/async-option-lists
Avoid including the selector's own value in the cache key, as demonstrated in this example, unless the functionality is specifically for auto-complete.
```javascript
// ❌ Bad: includes own value (unless auto-complete)
getCacheKey: props => `${props.rule?.field}-${props.value}`;
```
--------------------------------
### Define Fields and Initial Query State
Source: https://react-querybuilder.js.org/docs/tips/external-controls
Sets up the available fields for the query builder and defines the initial query structure. This is crucial for initializing the query state.
```javascript
const fields: Field[] = [
{ name: 'firstName', label: 'First Name' },
{ name: 'lastName', label: 'Last Name' },
];
const initialQuery: RuleGroupType = {
combinator: 'and',
rules: [
{ field: 'firstName', operator: '=', value: 'Steve' },
{ field: 'lastName', operator: '=', value: 'Vai' },
],
};
```
--------------------------------
### Custom JSONata Rule Processor Example
Source: https://react-querybuilder.js.org/docs/utils/export
Implement a custom rule processor for JSONata to handle specific data types like dates. This example demonstrates checking a 'datatype' property and using `$toMillis`.
```typescript
const customRuleProcessor: RuleProcessor = (rule, options) => {
// `datatype` is a non-standard property of the field, used for this example only.
// Replace this condition with your own logic to determine if the value is a date.
if (options?.fieldData?.datatype === 'date') {
return `$toMillis(${rule.field}) ${rule.operator} $toMillis("${rule.value}")`;
}
return defaultRuleProcessorJSONata(rule, options);
};
```
--------------------------------
### Enabling Shift Actions
Source: https://react-querybuilder.js.org/docs/changelog
Illustrates how to enable the `showShiftActions` prop to allow users to rearrange rules and groups.
```javascript
;
```
--------------------------------
### Import datetimeRuleProcessorSQL
Source: https://react-querybuilder.js.org/docs/datetime
Import the SQL rule processor for date/time fields. Choose the import based on your preferred date-time library (Day.js, date-fns, or Luxon).
```javascript
import { datetimeRuleProcessorSQL } from '@react-querybuilder/datetime/dayjs';
// Other options:
// import { datetimeRuleProcessorSQL } from '@react-querybuilder/datetime/date-fns';
// import { datetimeRuleProcessorSQL } from '@react-querybuilder/datetime/luxon';
```
--------------------------------
### Custom Rule Processor for Parameterized SQL
Source: https://react-querybuilder.js.org/docs/utils/export
Generate named parameters for parameterized SQL formats using `getNextNamedParam`. This example demonstrates creating parameterized SQL for a case-insensitive 'has' operator, similar to the Oracle SQL example.
```javascript
const customRuleProcessor: RuleProcessor = (rule, options) => {
if (rule.operator === 'has') {
// TIP: `getNextNamedParam` can be called multiple times in case your SQL
// requires multiple unique parameters (e.g., in a "between" condition).
// Each call will generate a new name.
const paramName = options.getNextNamedParam!(rule.field);
return {
sql: `UPPER(${rule.field}) LIKE UPPER('%' || ${options.paramPrefix}${paramName} || '%')`,
params: { [paramName]: rule.value },
};
}
return defaultRuleProcessorSQLParameterized(rule, options);
};
formatQuery(query, { format: 'parameterized_named', ruleProcessor: customRuleProcessor });
/*
{
sql: "(UPPER(firstName) LIKE UPPER('%' || :firstName_1 || '%') and lastName = :lastName_1)",
params: {
firstName_1: "S",
lastName_1: "Vai"
}
}
*/
```
--------------------------------
### Independent Combinators
Source: https://react-querybuilder.js.org/docs/components/querybuilder
Explanation and examples of using independent combinators for a more natural query structure.
```APIDOC
## Independent combinators
Props specifying `RuleGroupTypeAny` are inferred as [`RuleGroupType` or `RuleGroupTypeIC`](/docs/typescript.md#rules-and-groups). `RuleGroupTypeIC` queries use "independent combinators."
This places combinator values between each neighboring rule/group pair (every odd-numbered index). Similar to [`showCombinatorsBetweenRules`](#showcombinatorsbetweenrules), but each combinator is independently controlled. Users often find this more natural as it mirrors natural language query expression.
A standard query (`RuleGroupType`) might look like this:
```javascript
const query = {
combinator: 'and',
rules: [
{ field: 'f1', operator: '=', value: 'v1' },
{ field: 'f2', operator: '=', value: 'v2' },
],
};
```
The same query using independent combinators would look like this:
```javascript
const query = {
rules: [
{ field: 'f1', operator: '=', value: 'v1' },
'and',
{ field: 'f2', operator: '=', value: 'v2' },
],
};
```
Click [here](/demo#independentCombinators=true) to load the demo with a query using independent combinators.
```
--------------------------------
### Customizing Accessible Descriptions
Source: https://react-querybuilder.js.org/docs/changelog
Provides an example of using `accessibleDescriptionGenerator` to customize the title attribute for accessibility.
```javascript
const accessibleDescriptionGenerator = (
{ id, combinator, ಇಂಡex, depth } // ... other properties
) => {
return `Group ${id} (${combinator}, depth ${depth})`;
};
```
--------------------------------
### Configure Pragmatic Drag and Drop with QueryBuilderDnD
Source: https://react-querybuilder.js.org/docs/dnd
Set up the QueryBuilderDnD context provider with the Pragmatic Drag and Drop adapter. This enables drag-and-drop functionality for reordering rules and groups.
```jsx
import { QueryBuilderDnD } from '@react-querybuilder/dnd';
import { createPragmaticDndAdapter } from '@react-querybuilder/dnd/pragmatic-dnd';
import {
draggable,
dropTargetForElements,
monitorForElements,
} from '@atlaskit/pragmatic-drag-and-drop/element/adapter';
import { combine } from '@atlaskit/pragmatic-drag-and-drop/combine';
import { QueryBuilder } from 'react-querybuilder';
const pragmaticDndAdapter = createPragmaticDndAdapter({
draggable,
dropTargetForElements,
monitorForElements,
combine,
});
const App = () => (
);
```
--------------------------------
### Callback Props with Meta Parameter
Source: https://react-querybuilder.js.org/docs/changelog
Example of a callback prop receiving an additional 'meta' parameter, including 'fieldData'.
```javascript
const getOperators = ({ field, fieldData, ...otherMeta }) => {
// Use fieldData here
return ['=', '!=', '<', '>', ...];
};
```
--------------------------------
### Create DnD Kit Adapter for React Query Builder
Source: https://react-querybuilder.js.org/docs/changelog
Use `createDndKitAdapter` to wrap `@dnd-kit/core` exports into a `DndAdapter`. This provides a first-class alternative to `react-dnd` for drag-and-drop functionality.
```javascript
import { createDndKitAdapter } from "react-querybuilder/dnd";
const dndAdapter = createDndKitAdapter({
// ...@dnd-kit/core exports
});
;
```
--------------------------------
### useQueryBuilderSetup
Source: https://react-querybuilder.js.org/docs/utils/hooks
Merges props and context with defaults and generates actions for the QueryBuilder.
```APIDOC
## `useQueryBuilderSetup`
### Description
Called by the internal component rendered by `QueryBuilder`. Merges props and context values with the defaults and generates actions.
### Usage Note
This hook is unlikely to be necessary unless you're reimplementing the entire `QueryBuilder` component structure.
### Parameters
#### Request Body
- **props** (QueryBuilderProps) - Required - Properties for the QueryBuilder.
### Returns
- **qbId** (any) - The unique identifier for the query builder instance.
- **rqbContext** (ReturnType) - The merged context values.
- **fields** (OptionList) - List of available fields.
- **fieldMap** (Record) - A map of field names to field configurations.
- **combinators** (OptionList) - List of available combinators.
- **getOperatorsMain** (function) - Function to get operators for a given field.
- **getRuleDefaultOperator** (function) - Function to get the default operator for a field.
- **getValueEditorTypeMain** (function) - Function to get the value editor type for a field and operator.
- **getValueSourcesMain** (function) - Function to get value sources for a field and operator.
- **getValuesMain** (function) - Function to get possible values for a field and operator.
- **getRuleDefaultValue** (function) - Function to get the default value for a rule.
- **getInputTypeMain** (function) - Function to get the input type for a field and operator.
- **createRule** (function) - Function to create a new rule.
- **createRuleGroup** (function) - Function to create a new rule group.
```
--------------------------------
### Format Query with Value Sources as Fields
Source: https://react-querybuilder.js.org/docs/api/export
Demonstrates how rules with 'valueSource: "field"' are formatted, resulting in no parameters being generated for those specific conditions.
```javascript
const pf = formatQuery(
{
combinator: 'and',
rules: [
{ field: 'firstName', operator: '=', value: 'lastName', valueSource: 'field' },
{ field: 'firstName', operator: 'beginsWith', value: 'middleName', valueSource: 'field' },
],
},
'parameterized_named'
);
/*
Output (JSON object):
{
"sql": "(firstName = lastName and firstName like middleName || '%')",
"params": {}
}
*/
```
--------------------------------
### Enable Numbered Parameters with Prefix
Source: https://react-querybuilder.js.org/docs/api/export
Configure parameterized SQL format to use numbered placeholders prefixed with a custom string. Useful for databases that support numbered parameters.
```javascript
const p = formatQuery(query, {
format: 'parameterized',
paramPrefix: '$',
numberedParams: true,
});
/*
p.sql === "(firstName = $1 and lastName = $2)"
*/
```
--------------------------------
### Independent Combinators Query Structure
Source: https://react-querybuilder.js.org/docs/components/querybuilder
Example of a query object using `RuleGroupTypeIC` which places combinators between rules, allowing independent control.
```typescript
const query: RuleGroupTypeIC = {
rules: [
{ field: 'f1', operator: '=', value: 'v1' },
'and',
{ field: 'f2', operator: '=', value: 'v2' },
],
};
```
--------------------------------
### Legacy SQL Value Processor
Source: https://react-querybuilder.js.org/docs/utils/export
Demonstrates the legacy value processor signature for SQL format. This signature is not recommended due to limited arguments, making it harder to fall back to default processors.
```javascript
const query = {
combinator: 'and',
not: false,
rules: [
{ field: 'instrument', operator: 'in', value: ['Guitar', 'Vocals'] },
{ field: 'lastName', operator: '=', value: 'Vai' },
],
};
const customValueProcessor = (field, operator, value) => {
if (operator === 'in') {
// Assuming `value` is an array, such as from a multi-select
return `(${value.map(v => `'${v.trim()}'`).join(',')})`;
}
return defaultValueProcessor(field, operator, value);
};
formatQuery(query, { format: 'sql', valueProcessor: customValueProcessor });
/*
"(instrument in ('Guitar','Vocals') and lastName = 'Vai')"
*/
```
--------------------------------
### Configure Cache Time-to-Live (cacheTTL)
Source: https://react-querybuilder.js.org/docs/tips/async-option-lists
Set the cache time-to-live in milliseconds using `cacheTTL`. The default is 30 minutes. Setting it to `0` disables caching.
```typescript
// 30 minutes (default)
const cacheTTL = 1_800_000;
// 5 minutes: m s ms
const cacheTTL = 5 * 60 * 1000;
// Disable caching (cache will be populated but immediately outdated)
const cacheTTL = 0;
const ValueSelectorAsync = (props: ValueSelectorProps) => {
const asyncProps = useAsyncOptionList(props, { cacheTTL, loadOptionList });
return ;
};
```