### Run Sandbox Locally with npm
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/packages/sandbox/README.md
Install and start the sandbox demo locally using npm. This method downloads packages from NPM.
```sh
npm run preinstall
npm i
npm start
```
--------------------------------
### Minimal TypeScript Example with Function Component
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/README.md
This snippet shows a basic setup of the query builder using a functional component in TypeScript. It includes defining the configuration, initial query value, and handling changes. It also demonstrates rendering the builder and displaying the query in different formats.
```typescript
import React, { useState, useCallback } from "react";
// >>>
import type { JsonGroup, Config, ImmutableTree, BuilderProps } from '@react-awesome-query-builder/ui';
import { Utils as QbUtils, Query, Builder, BasicConfig } from '@react-awesome-query-builder/ui';
import '@react-awesome-query-builder/ui/css/styles.css';
const InitialConfig = BasicConfig;
// <<<
// You need to provide your own config. See below 'Config format'
const config: Config = {
...InitialConfig,
fields: {
qty: {
label: "Qty",
type: "number",
fieldSettings: {
min: 0
},
valueSources: ["value"],
preferWidgets: ["number"]
},
price: {
label: "Price",
type: "number",
valueSources: ["value"],
fieldSettings: {
min: 10,
max: 100
},
preferWidgets: ["slider", "rangeslider"]
},
name: {
label: 'Name',
type: 'text',
},
color: {
label: "Color",
type: "select",
valueSources: ["value"],
fieldSettings: {
listValues: [
{ value: "yellow", title: "Yellow" },
{ value: "green", title: "Green" },
{ value: "orange", title: "Orange" }
]
}
},
is_promotion: {
label: "Promo?",
type: "boolean",
operators: ["equal"],
valueSources: ["value"]
}
}
};
// You can load query value from your backend storage (for saving see `Query.onChange()`)
const queryValue: JsonGroup = { id: QbUtils.uuid(), type: "group" };
const DemoQueryBuilder: React.FC = () => {
const [state, setState] = useState({
tree: QbUtils.loadTree(queryValue),
config: config
});
const onChange = useCallback((immutableTree: ImmutableTree, config: Config) => {
// Tip: for better performance you can apply `throttle` - see `packages/examples/src/demo`
setState(prevState => ({ ...prevState, tree: immutableTree, config: config }));
const jsonTree = QbUtils.getTree(immutableTree);
console.log(jsonTree);
// `jsonTree` can be saved to backend, and later loaded to `queryValue`
}, []);
const renderBuilder = useCallback((props: BuilderProps) => (
), []);
return (
Query string: "
{JSON.stringify(QbUtils.queryString(state.tree, state.config))}
MongoDb query: "
{JSON.stringify(QbUtils.mongodbFormat(state.tree, state.config))}
SQL where: "
{JSON.stringify(QbUtils.sqlFormat(state.tree, state.config))}
JsonLogic: "
{JSON.stringify(QbUtils.jsonLogicFormat(state.tree, state.config))}
);
};
export default DemoQueryBuilder;
```
--------------------------------
### Install Fluent UI Builder Package
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/packages/fluent/README.md
Installs the @react-awesome-query-builder/fluent package. This command should be run after installing the peer dependencies.
```bash
npm i @react-awesome-query-builder/fluent --save
```
--------------------------------
### Minimal JavaScript Example with Class Component
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/README.md
A basic JavaScript example demonstrating how to use the QueryBuilder with a class component. This snippet shows the essential setup for integrating the builder into a React application.
```javascript
import React from 'react';
import ReactDOM from 'react-dom';
import { Query, Builder } from '@react-awesome-query-builder/core';
import '@react-awesome-query-builder/core/lib/styles.css';
const config = {
fields: {
"name": {
"label": "Name",
"type": "string"
},
"age": {
"label": "Age",
"type": "number"
},
"city": {
"label": "City",
"type": "string",
"enum": {
"ny": "New York",
"la": "Los Angeles"
}
}
}
};
class App extends React.Component {
state = {
tree: Query.defaultTree(config.fields)
};
render() {
return (
this.setState({ tree })} tree={this.state.tree} />
);
}
}
ReactDOM.render(, document.getElementById('root'));
```
--------------------------------
### Install Core Package
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/packages/core/README.md
Install the core package using npm.
```bash
npm i @react-awesome-query-builder/core --save
```
--------------------------------
### Run Demo App
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/packages/examples/README.md
Execute this command from the root of the cloned repository to start the demo application. Open http://localhost:3001 in your browser.
```sh
pnpm start
```
--------------------------------
### Install @react-awesome-query-builder/ui
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/packages/ui/README.md
Install the UI package using npm. This command adds the necessary components and styles for the query builder.
```bash
npm i @react-awesome-query-builder/ui --save
```
--------------------------------
### Import Fluent UI Components and Configuration
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/packages/fluent/README.md
Imports necessary types, components, and configuration for using the Fluent UI builder. This setup is required for TypeScript examples and general usage.
```typescript
import type { JsonGroup, Config, ImmutableTree, BuilderProps } from '@react-awesome-query-builder/fluent'; // for TS example
import { Query, Builder, Utils as QbUtils } from '@react-awesome-query-builder/fluent';
import { FluentUIConfig, FluentUIWidgets } from '@react-awesome-query-builder/fluent';
import '@react-awesome-query-builder/fluent/css/styles.css';
const InitialConfig = FluentUIConfig;
```
--------------------------------
### Minimal JavaScript Example with Class Component
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/README.md
This snippet shows a basic setup for using the Query Builder component within a React class component. It includes necessary imports, a sample configuration, and the component's render and change handlers. Ensure you provide your own config object.
```javascript
import React, {Component} from 'react';
// >>>
import { Utils as QbUtils, Query, Builder, BasicConfig } from '@react-awesome-query-builder/ui';
import '@react-awesome-query-builder/ui/css/styles.css';
const InitialConfig = BasicConfig;
// <<<
// You need to provide your own config. See below 'Config format'
const config = {
...InitialConfig,
fields: {
qty: {
label: 'Qty',
type: 'number',
fieldSettings: {
min: 0,
},
valueSources: ['value'],
preferWidgets: ['number'],
},
price: {
label: 'Price',
type: 'number',
valueSources: ['value'],
fieldSettings: {
min: 10,
max: 100,
},
preferWidgets: ['slider', 'rangeslider'],
},
name: {
label: 'Name',
type: 'text',
},
color: {
label: 'Color',
type: 'select',
valueSources: ['value'],
fieldSettings: {
listValues: [
{ value: 'yellow', title: 'Yellow' },
{ value: 'green', title: 'Green' },
{ value: 'orange', title: 'Orange' }
],
}
},
is_promotion: {
label: 'Promo?',
type: 'boolean',
operators: ['equal'],
valueSources: ['value'],
},
}
};
// You can load query value from your backend storage (for saving see `Query.onChange()`)
const queryValue = {"id": QbUtils.uuid(), "type": "group"};
class DemoQueryBuilder extends Component {
state = {
tree: QbUtils.loadTree(queryValue),
config: config
};
render = () => (
{this.renderResult(this.state)}
)
renderBuilder = (props) => (
)
renderResult = ({tree: immutableTree, config}) => (
Query string:
{JSON.stringify(QbUtils.queryString(immutableTree, config))}
MongoDb query:
{JSON.stringify(QbUtils.mongodbFormat(immutableTree, config))}
SQL where:
{JSON.stringify(QbUtils.sqlFormat(immutableTree, config))}
JsonLogic:
{JSON.stringify(QbUtils.jsonLogicFormat(immutableTree, config))}
)
onChange = (immutableTree, config) => {
// Tip: for better performance you can apply `throttle` - see `packages/examples/src/demo`
this.setState({tree: immutableTree, config: config});
const jsonTree = QbUtils.getTree(immutableTree);
console.log(jsonTree);
// `jsonTree` can be saved to backend, and later loaded to `queryValue`
}
}
export default DemoQueryBuilder;
```
--------------------------------
### Install Peer Dependencies for Fluent UI
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/packages/fluent/README.md
Installs the necessary Fluent UI packages as peer dependencies. Ensure these are installed before using the fluent UI builder.
```bash
npm i @fluentui/react @fluentui/react-icons @fluentui/font-icons-mdl2 --save
```
--------------------------------
### Run All Tests
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/packages/tests/README.md
Install dependencies and run all tests. Coverage reports are generated in the coverage directory.
```sh
pnpm i
pnpm test
```
--------------------------------
### Install Bootstrap Package
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/packages/bootstrap/README.md
Install the @react-awesome-query-builder/bootstrap package to use Bootstrap widgets.
```bash
npm i @react-awesome-query-builder/bootstrap --save
```
--------------------------------
### Minimal TypeScript Example with Function Component
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/README.md
A basic TypeScript example demonstrating the use of the QueryBuilder with a function component. This snippet illustrates the setup for a TypeScript-based React project.
```typescript
import React, { useState } from 'react';
import ReactDOM from 'react-dom';
import { Query, Builder, Config } from '@react-awesome-query-builder/core';
import '@react-awesome-query-builder/core/lib/styles.css';
const config: Config = {
fields: {
"name": {
"label": "Name",
"type": "string"
},
"age": {
"label": "Age",
"type": "number"
},
"city": {
"label": "City",
"type": "string",
"enum": {
"ny": "New York",
"la": "Los Angeles"
}
}
}
};
const App = () => {
const [tree, setTree] = useState(Query.defaultTree(config.fields));
return (
);
};
ReactDOM.render(, document.getElementById('root'));
```
--------------------------------
### Install pnpm
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/CONTRIBUTING.md
Install the pnpm package manager globally. This is a prerequisite for setting up the development environment.
```bash
npm install -g pnpm@9
```
--------------------------------
### Install MUI Package
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/packages/mui/README.md
Install the @react-awesome-query-builder/mui package to use MUI widgets with the query builder.
```bash
npm i @react-awesome-query-builder/mui --save
```
--------------------------------
### Bootstrap Query Builder Setup
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/packages/bootstrap/README.md
Import necessary components and CSS for using the Bootstrap widgets. Ensure Bootstrap CSS and custom styles are imported.
```javascript
// >>>
import type { JsonGroup, Config, ImmutableTree, BuilderProps } from '@react-awesome-query-builder/bootstrap'; // for TS example
import { Query, Builder, Utils as QbUtils } from '@react-awesome-query-builder/bootstrap';
import { BootstrapConfig, BootstrapWidgets } from '@react-awesome-query-builder/bootstrap';
import "bootstrap/dist/css/bootstrap.min.css";
import '@react-awesome-query-builder/bootstrap/css/styles.css';
const InitialConfig = BootstrapConfig;
// <<<
```
--------------------------------
### Install MUI Peer Dependencies
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/packages/mui/README.md
Install the necessary Material-UI peer dependencies before installing the MUI package for the query builder.
```bash
npm i @mui/material @emotion/react @emotion/styled @mui/icons-material @mui/x-date-pickers @mui/base --save
```
--------------------------------
### Core Query Builder Usage Example
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/packages/core/README.md
Demonstrates initializing the core, loading a tree from JSON, adding a rule, and exporting the tree in multiple formats. Requires importing necessary types and utilities from the core package.
```javascript
import {
CoreConfig,
Utils,
// types
TreeStore,
TreeState,
TreeActions,
InputAction,
JsonTree
} from '@react-awesome-query-builder/core';
// config
const config = {
...CoreConfig,
fields: {
name: {
label: 'Name',
type: 'text',
},
age: {
label: 'Age',
type: 'number',
}
}
};
// load from JSON
const initialTree = Utils.loadTree({
id: '00001',
type: 'group',
children1: [
{
id: '00002',
type: 'rule',
properties: {
field: 'age',
operator: 'greater_or_equal',
value: [18],
valueSrc: ['value']
}
}
]
});
// or import from jsonLogic
// const initialTree = Utils.loadFromJsonLogic({
// 'and': [
// {
// '<=': [
// {var: 'age'},
// 18
// ]
// }
// ]
// }, config);
// create store to manipulate tree on backend
const reducer = TreeStore(config);
let state: TreeState = reducer({tree: initialTree});
// add rule `name == 'denis'`
const rootPath = [ state.tree.get('id') as string ];
const action = TreeActions.tree.addRule(config, rootPath, {
field: 'name',
operator: 'equal',
value: ['denis'],
valueSrc: ['value'],
valueType: ['text']
});
state = reducer(state, action);
// export
const tree = Utils.getTree(state.tree);
const { logic } = Utils.jsonLogicFormat(state.tree, config);
const sql = Utils.sqlFormat(state.tree, config);
const spel = Utils.sqlFormat(state.tree, config);
const mongo = Utils.mongodbFormat(state.tree, config);
const elastic = Utils.elasticSearchFormat(state.tree, config);
console.log({ tree, logic, sql, spel, mongo, elastic });
```
--------------------------------
### Install SQL Package
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/packages/sql/README.md
Install the SQL package for React Awesome Query Builder using npm.
```sh
npm i @react-awesome-query-builder/sql --save
```
--------------------------------
### Install Ant Design Widgets Package
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/packages/antd/README.md
Install the @react-awesome-query-builder/antd package to use Ant Design widgets.
```bash
npm i @react-awesome-query-builder/antd --save
```
--------------------------------
### Install Ant Design Dependencies
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/packages/antd/README.md
Install Ant Design and its icons as peer dependencies before installing the Ant Design widgets package.
```bash
npm i antd @ant-design/icons --save
```
--------------------------------
### Install Material UI Package
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/packages/material/README.md
Install the @react-awesome-query-builder/material package to add Material-UI v4 widgets to your query builder.
```bash
npm i @react-awesome-query-builder/material --save
```
--------------------------------
### Fetch Selected Values OnInit Example
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/CONFIG.adoc
Demonstrates how to fetch selected values initially to resolve their titles for UI display. The asyncFetch function should handle an array of selected values.
```javascript
asyncFetch(['#FFFF00', '#008000', '#20B2A2'])
```
```javascript
asyncFetch(['#FFFF00'])
```
--------------------------------
### Install Bootstrap Dependencies
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/packages/bootstrap/README.md
Install the peer dependencies required for Bootstrap integration, including Bootstrap itself, reactstrap, Popper.js, and Font Awesome.
```bash
npm i bootstrap reactstrap @popperjs/core @fortawesome/fontawesome-svg-core @fortawesome/free-solid-svg-icons @fortawesome/react-fontawesome --save
```
--------------------------------
### Install Material UI Peer Dependencies
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/packages/material/README.md
Before installing the material package, ensure you have the necessary Material-UI v4 peer dependencies installed. These are required for the widgets to function correctly.
```bash
npm i @material-ui/core @material-ui/lab @material-ui/icons @material-ui/pickers --save
```
--------------------------------
### Configuring a Text Widget
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/CONFIG.adoc
Example of configuring a text widget with custom properties like maxLength. This is useful for limiting user input in text fields.
```javascript
{
text: {
type: 'text',
valueSrc: 'value',
factory: (props) => ,
formatValue: (val, _fieldDef, _wgtDef, isForDisplay) => (isForDisplay ? val.toString() : JSON.stringify(val)),
mongoFormatValue: (val, _fieldDef, _wgtDef) => (val),
// Options:
valueLabel: "Text",
valuePlaceholder: "Enter text",
// Custom props (https://ant.design/components/input/):
customProps: {
maxLength: 3
},
},
..,
}
```
--------------------------------
### Importing Ant Design Widgets
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/CONFIG.adoc
Example of importing locale settings for Russian and specific Ant Design widgets for use with the query builder.
```javascript
import ru_RU from 'antd/es/locale/ru_RU';
import { ruRU } from '@material-ui/core/locale'; //v4
import { ruRU as muiRuRU } from '@mui/material/locale';
const { FieldCascader, FieldDropdown, FieldTreeSelect } = AntdWidgets;
```
--------------------------------
### Basic Configuration Components
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/CONFIG.adoc
Imports essential components like conjunctions, operators, widgets, and types from the AntdConfig for basic query builder setup.
```javascript
const {
conjunctions: {
AND,
OR
},
operators: {
equal,
not_equal,
less,
less_or_equal,
greater,
greater_or_equal,
like,
not_like,
starts_with,
ends_with,
between,
not_between,
is_null,
is_not_null,
is_empty,
is_not_empty,
select_equals, // like `equal`, but for select
select_not_equals,
select_any_in,
select_not_any_in,
multiselect_contains,
multiselect_not_contains,
multiselect_equals, // like `equal`, but for multiselect
multiselect_not_equals,
proximity, // complex operator with options
},
widgets: {
text,
textarea, // multiline text
number,
price, // same as number but with decimal separator etc.
slider,
rangeslider, // missing in `BasicConfig`, `BootstrapConfig`, `FluentUIConfig`
select,
multiselect,
treeselect, // present only in `AntdConfig`
treemultiselect, // present only in `AntdConfig`
date,
time,
datetime,
boolean,
field, // to compare field with another field of same type
func, // to compare field with result of function
},
types: {
text,
number,
date,
time,
datetime,
select,
multiselect,
treeselect,
treemultiselect,
boolean,
},
settings,
ctx,
} = AntdConfig;
```
--------------------------------
### Load Empty Tree in Ternary Mode
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/README.md
Initializes an empty tree structure for ternary mode using `QbUtils.uuid()` and `QbUtils.loadTree()`. This is useful for starting with a blank conditional logic structure.
```javascript
import { Utils as QbUtils, JsonSwitchGroup } from '@react-awesome-query-builder/ui';
const emptyJson: JsonSwitchGroup = { id: QbUtils.uuid(), type: "switch_group", };
const tree = QbUtils.loadTree(emptyJson);
```
--------------------------------
### Example CSS Import for Bootstrap UI in v6.0.0
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/README.md
If using Bootstrap widgets, explicitly import Bootstrap's CSS file.
```javascript
import "bootstrap/dist/css/bootstrap.min.css";
```
--------------------------------
### Example CSS Import for Ant Design UI in v6.0.0
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/README.md
For Ant Design UI, import styles directly from the Ant Design package to ensure correct styling.
```javascript
import '@react-awesome-query-builder/antd/css/styles.css';
```
--------------------------------
### Static List Values Example
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/CONFIG.adoc
Defines a static list of values for widgets like 'select' and 'multiselect'. Values can be grouped using 'groupTitle'.
```javascript
[{value: 'yellow', title: 'Yellow'}, {value: 'green', title: 'Green'}]
```
```javascript
{ yellow: 'Yellow', green: 'Green' }
```
```javascript
[{value: 'red', groupTitle: 'Warm colors'}, {value: 'orange', groupTitle: 'Warm colors'}]
```
--------------------------------
### Example Import for Ant Design UI in v6.0.0
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/README.md
When using Ant Design, import all necessary components from the `@react-awesome-query-builder/antd` package. This includes core, UI, and Ant Design specific configurations.
```javascript
import {Utils, Query, Builder, AntdConfig} from '@react-awesome-query-builder/antd';
```
--------------------------------
### Extend CSS Variable Generation (MUI Example)
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/CONFIG.adoc
Provide a custom function to extend the default CSS variable generation for MUI themes. This allows adding custom variables while retaining default behavior.
```javascript
generateCssVars.mui = (theme, config) => ({ ...config.ctx.generateCssVars(theme, config), "--group-background": theme.palette.grey["200"] })
```
--------------------------------
### Function Definition Example
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/CONFIG.adoc
Define a custom function, 'lower', with its SQL and MongoDB equivalents, return type, and arguments. This allows for custom data transformations within the query builder.
```javascript
{
lower: {
label: 'Lowercase',
sqlFunc: 'LOWER',
mongoFunc: '$toLower',
returnType: 'text',
args: {
str: {
type: 'text',
valueSources: ['value', 'field'],
}
}
},
..
}
```
--------------------------------
### Static Tree Values Example
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/CONFIG.adoc
Defines a static list of values for 'treeselect' and 'treemultiselect' widgets. Values can have parent-child relationships or be defined with nested children.
```javascript
[{value: 'warm', title: 'Warm colors'}, {value: 'red', title: 'Red', parent: 'warm'}, {value: 'orange', title: 'Orange', parent: 'warm'}]
```
```javascript
[{value: 'warm', title: 'Warm colors', children: [ {value: 'red', title: 'Red'}, {value: 'orange', title: 'Orange'} ]}]
```
--------------------------------
### Configure Ternary Mode Case Values
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/README.md
Set up `caseValueField` in `config.settings` to define how case values are rendered, using options like `select` with `listValues`. This example uses tags as case values.
```javascript
const config: Config = {
...InitialConfig,
fields,
settings: {
...InitialConfig.settings,
caseValueField: {
type: "select",
valueSources: ["value"],
fieldSettings: {
listValues: [
{ value: "tag1", title: "Tag #1" },
{ value: "tag2", title: "Tag #2" },
],
},
mainWidgetProps: {
valueLabel: "Then",
valuePlaceholder: "Then",
},
},
canRegroupCases: true,
maxNumberOfCases: 10,
}
};
```
--------------------------------
### Building and Verifying Config with Context
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/CONFIG.adoc
Shows how to merge basic configuration with custom fields and context, then compress it and decompress to verify.
```javascript
import merge from "lodash/merge"
const ctx = {
validateFirstName: (val) => {
return (val.length < 10);
},
};
const config = merge({}, BasicConfig, {
fields: {
firstName: {
type: "text",
fieldSettings: {
validateValue: "validateFirstName",
}
},
},
ctx,
});
const zipConfig = Utils.ConfigUtils.compressConfig(config, BasicConfig);
const config2 = Utils.ConfigUtils.decompressConfig(zipConfig, BasicConfig, ctx); // should be same as `config`
```
--------------------------------
### Run Sandbox Simple Locally with pnpm
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/packages/sandbox_simple/README.md
Execute this command from the root of the cloned repository to run the sandbox-simple demo using local packages.
```sh
pnpm sandbox-js
```
--------------------------------
### Basic Configuration Structure
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/CONFIG.adoc
This snippet shows the basic structure of a configuration object, including importing and extending from predefined UI configurations. It demonstrates how to reuse a base configuration and add custom fields.
```javascript
import {BasicConfig} from '@react-awesome-query-builder/ui';
import {AntdConfig} from '@react-awesome-query-builder/antd';
import {MuiConfig} from '@react-awesome-query-builder/mui';
import {MaterialConfig} from '@react-awesome-query-builder/material';
import {BootstrapConfig} from "@react-awesome-query-builder/bootstrap";
import {FluentUIConfig} from "@react-awesome-query-builder/fluent";
const InitialConfig = BasicConfig; // or AntdConfig or MuiConfig or BootstrapConfig or FluentUIConfig
const myConfig = {
...InitialConfig, // reuse basic config
fields: {
stock: {
label: 'In stock',
type: 'boolean',
},
// ... my other fields
}
};
```
--------------------------------
### Run Sandbox Next.js App Locally (pnpm)
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/packages/sandbox_next/README.md
Execute this command from the root of the cloned repository to run the demo app locally using pnpm. This will utilize local packages.
```sh
pnpm sandbox-next
```
--------------------------------
### Custom Function Rendering for Ant Design
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/CONFIG.adoc
Customize how functions are rendered, with specific examples for Ant Design's FieldSelect and FieldDropdown.
```javascript
renderFunc: (props) =>
```
--------------------------------
### Custom Operator Rendering for Ant Design
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/CONFIG.adoc
Customize how operators are rendered, with specific examples for Ant Design's FieldSelect and FieldDropdown.
```javascript
renderOperator: (props) =>
```
--------------------------------
### Basic Functions Configuration
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/CONFIG.adoc
Demonstrates how to import and use basic functions from '@react-awesome-query-builder/ui' within your configuration. This is useful for extending the available query functions.
```javascript
import { BasicFuncs } from '@react-awesome-query-builder/ui';
const config = {
//...
funcs: {
LINEAR_REGRESSION: BasicFuncs.LINEAR_REGRESSION,
LOWER: BasicFuncs.LOWER,
}
};
```
--------------------------------
### Manual Package Publish
Source: https://github.com/ukrbublik/react-awesome-query-builder/wiki/Internal-commands
Publishes all packages recursively with public access using pnpm.
```sh
pnpm -r publish --access public
```
--------------------------------
### Configure Operators (e.g., Equal)
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/CONFIG.adoc
Sets up comparison operators like 'equal'. Customize labels, reversed operators, formatting, and backend-specific formats (e.g., MongoDB).
```javascript
{
equal: {
label: 'equals',
reversedOp: 'not_equal',
labelForFormat: '==',
cardinality: 1,
formatOp: (field, _op, value, _valueSrc, _valueType, opDef) => `${field} ${opDef.labelForFormat} ${value}`,
mongoFormatOp: (field, op, value) => ({ [field]: { '$eq': value } }),
},
..
}
```
--------------------------------
### Configuration with Context
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/CONFIG.adoc
This snippet demonstrates how to define a configuration object for the query builder, including custom render functions and widget logic that utilize a provided context (`ctx`). The `ctx` object contains essential modules and utilities like React.createElement, custom components, and moment.js.
```javascript
const config = {
settings: {
renderButton: (props, {RCE, W: {VanillaButton}}) => RCE(VanillaButton, props),
},
widgets: {
date: {
jsonLogic: function (val, fieldDef, wgtDef) {
return this.utils.moment(val, wgtDef.valueFormat).toDate();
},
},
},
ctx: {
RCE: React.createElement,
W: {
VanillaButton,
},
utils: {
moment,
},
}
};
```
--------------------------------
### Add Custom JsonLogic Operations
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/README.md
If you import a custom version of json-logic-js, you need to add required operations. This example shows how to import JL and add operations.
```javascript
import JL from "json-logic-js";
Utils.JsonLogicUtils.addRequiredJsonLogicOperations(JL);
// console.log(JL.apply({ "now": [] }));
```
--------------------------------
### Serializing Config with JS Functions to String
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/CONFIG.adoc
Demonstrates how to serialize a configuration object containing JavaScript functions to a string using `serialize-javascript` for later deserialization with `eval()`.
```javascript
import { VanillaWidgets } from '@react-awesome-query-builder/ui';
const { VanillaButton } = VanillaWidgets;
import moment from "moment";
const config = {
settings: {
renderButton: (props) => ,
},
widgets: {
date: {
jsonLogic: (val, fieldDef, wgtDef) => moment(val, wgtDef.valueFormat).toDate(),
},
},
};
```
--------------------------------
### Override CSS Variable Generation (MUI Example)
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/CONFIG.adoc
Provide a custom function to override or extend the generation of CSS variables for MUI themes. This allows fine-grained control over theme variables.
```javascript
generateCssVars.mui = (theme, config) => ({ "--group-background": theme.palette.background.paper })
```
--------------------------------
### Run Sandbox Locally with pnpm
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/packages/sandbox/README.md
Execute the TypeScript sandbox demo locally using pnpm. This command utilizes local packages for development.
```sh
pnpm sandbox-ts
```
--------------------------------
### Context Object Shape for Configuration
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/CONFIG.adoc
Illustrates the structure of the context object (`ctx`), including provided utilities, custom components, and custom validation/rendering functions.
```javascript
const ctx = {
// provided in BasicConfig:
RCE: React.createElement,
W: {
VanillaButton,
// ... other widgets provieded with the lib
},
utils: {
moment, // used in `formatValue`
SqlString, // used in `sqlFormatValue`
// ... other utils
},
// your custom extensions:
components: {
MyLabel, // used in `labelYes` and `labelNo` below
// ... other custom components used in JSXs in your config
},
validateFirstName: (val: string) => {
return (val.length < 10);
},
myRenderField: (props: FieldProps, _ctx: ConfigContext) => {
if (props.customProps?.["showSearch"]) {
return ;
} else {
return ;
}
},
autocompleteFetch, // see implementation in `/packages/sandbox_next/components/demo/config_ctx.tsx`
}
```
--------------------------------
### Render Builder Component
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/README.md
Render the Builder component inside Query.renderBuilder(). Wrapping in div.query-builder is necessary for drag-n-drop support. Add class .qb-lite for cleaner action buttons. Wrapping in div.query-builder-container is necessary for correct drag-n-drop support if the builder is inside a scrollable block.
```javascript
renderBuilder = (props) => (
)
```
--------------------------------
### Referring to Context Functions in zipConfig
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/CONFIG.adoc
Demonstrates how to reference custom functions and components defined in the context (`ctx`) by their names within the `zipConfig` structure.
```javascript
const zipConfig = {
fields: {
firstName: {
type: "text",
fieldSettings: {
validateValue: "validateFirstName",
}
},
in_stock: {
type: "boolean",
mainWidgetProps: {
labelYes: Yes,
labelNo: No,
}
},
autocomplete: {
type: "select",
fieldSettings: {
asyncFetch: "autocompleteFetch",
},
},
},
settings: {
renderField: "myRenderField",
renderButton: "W.VanillaButton",
useConfigCompress: true, // this is required
},
};
```
--------------------------------
### Import Ant Design Widgets and Configuration
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/packages/antd/README.md
Import necessary components and configurations for using Ant Design widgets. Import Ant Design CSS if using v4.
```javascript
// >>>
import type { JsonGroup, Config, ImmutableTree, BuilderProps } from '@react-awesome-query-builder/antd'; // for TS example
import { Query, Builder, Utils as QbUtils } from '@react-awesome-query-builder/antd';
import { AntdConfig, AntdWidgets } from '@react-awesome-query-builder/antd';
//import "antd/dist/antd.css"; // only for v4
import '@react-awesome-query-builder/antd/css/styles.css';
const InitialConfig = AntdConfig;
// <<<
```
--------------------------------
### Component API
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/README.md
The `` component is the main entry point for using the query builder. It accepts several props to configure its behavior, manage its state, and customize its rendering.
```APIDOC
## `` Component API
### Description
The `` component is the main entry point for using the query builder. It accepts several props to configure its behavior, manage its state, and customize its rendering.
### Props
- **`{...config}`** (object) - Destructured configuration object. See [`CONFIG`](/CONFIG.adoc) for details.
- **`value`** (Immutable.Map) - The current query value, represented in an internal [Immutable](https://immutable-js.github.io/immutable-js/) format.
- **`onChange`** (function) - A callback function invoked when the query value changes. It receives the following arguments:
- `value` (Immutable.Map): The new query value.
- `config` (object): The current configuration.
- `actionMeta` (object): Details about the action that triggered the change. See `ActionMeta` in [`index.d.ts`](/packages/core/modules/index.d.ts).
- `actions` (object): An object containing methods to programmatically trigger actions. See `Actions` in [`index.d.ts`](/packages/core/modules/index.d.ts).
- **`onInit`** (function) - A callback function invoked before the initial render. It receives the same arguments as `onChange`, but `actionMeta` will be undefined.
- **`renderBuilder`** (function) - A function that allows custom rendering of the query builder itself. It receives a `props` object, which should be passed to the `` component.
### Notes
- It is recommended to use `useCallback` for `onChange` and `renderBuilder` props for performance optimization.
- When integrating the query builder within components like Material-UI's `` or ``, or Fluent-UI's ``, specific props (`disableEnforceFocus`) and CSS adjustments might be necessary to manage focus and z-index.
- The `props` argument in `renderBuilder` provides access to `actions` and `dispatch` for programmatic action execution. Refer to `Actions` interface in [`index.d.ts`](/packages/core/modules/index.d.ts) for available actions and the `runActions()` example in [examples](/packages/examples/src/demo/index.tsx) for programmatic action invocation.
```
--------------------------------
### Default Configuration Object
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/CONFIG.adoc
This snippet shows a typical configuration object for the Query Builder, including settings for value sources, field sources, locale, custom renderers, and behavior flags.
```javascript
{
valueSourcesInfo: {
value: {
label: "Value"
},
field: {
label: "Field",
widget: "field",
},
func: {
label: "Function",
widget: "func",
}
},
fieldSources: ["field", "func"],
locale: {
moment: 'ru',
antd: ru_RU,
material: ruRU,
mui: muiRuRU,
},
renderField: (props) => ,
renderOperator: (props) => ,
renderFunc: (props) => ,
canReorder: true,
canRegroup: true,
maxNesting: 10,
showLabels: false,
showNot: true,
setOpOnChangeField: ['keep', 'default'],
customFieldSelectProps: {
showSearch: true
},
...
}
```
--------------------------------
### Fluent UI Theme Options
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/CONFIG.adoc
Customize the appearance of the query builder when using Fluent UI. Pass options compatible with Fluent UI's ThemeProvider to theme.fluent.
```javascript
theme.fluent: {}
```
--------------------------------
### Enable Server-Side Compression
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/README.md
To enable server-side config compression, set `config.settings.useConfigCompress` to `true`. This is necessary because config can contain functions not serializable to JSON.
```javascript
config.settings.useConfigCompress = true;
```
--------------------------------
### Config Save/Load
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/README.md
Utilities for compressing and decompressing the query builder configuration for efficient storage and retrieval.
```APIDOC
## compressConfig
### Description
Returns compressed config that can be serialized to JSON and saved on server. `ZipConfig` is a special format that contains only changes against `baseConfig`. `baseConfig` is a config you used as a base for constructing `config`, like `InitialConfig` in examples above. It depends on UI framework you choose - eg. if you use `@react-awesome-query-builder/mui`, please provide `MuiConfig` to `baseConfig`.
### Method
`Utils.ConfigUtils.compressConfig (config, baseConfig) -> ZipConfig`
```
```APIDOC
## decompressConfig
### Description
Converts `zipConfig` (compressed config you receive from server) to a full config that can be passed to ``. `baseConfig` is a config to be used as a base for constructing your config, like `InitialConfig` in examples above. [`ctx`](#ctx) is optional and can contain your custom functions and custom React components used in your config. If `ctx` is provided in 3rd argument, it will inject it to result config, otherwise will copy from basic config in 2nd argument. See [SSR](#ssr) for more info. Note that you should set `config.settings.useConfigCompress = true` in order for this function to work.
### Method
`Utils.ConfigUtils.decompressConfig (zipConfig, baseConfig, ctx?) -> Config`
```
--------------------------------
### Price Formatting Options
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/CONFIG.adoc
Configuration options for the 'price' widget to define thousands separator, decimal separator, decimal scale, prefix, suffix, and whether to allow negative numbers.
```javascript
thousandSeparator
```
```javascript
decimalSeparator
```
```javascript
decimalScale
```
```javascript
prefix
```
```javascript
suffix
```
```javascript
allowNegative
```
--------------------------------
### Importing and Destructuring UI Widgets
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/CONFIG.adoc
Import and destructure various widget sets from different UI libraries like Vanilla, Ant Design, Material UI, Bootstrap, and Fluent UI.
```javascript
import {VanillaWidgets} from '@react-awesome-query-builder/ui';
import {AntdWidgets} from '@react-awesome-query-builder/antd';
import {MuiWidgets} from '@react-awesome-query-builder/mui';
import {MaterialWidgets} from '@react-awesome-query-builder/material'; // MUI v4
import {BootstrapWidgets} from '@react-awesome-query-builder/bootstrap';
import {FluentUIWidgets} from "@react-awesome-query-builder/fluent";
const {
VanillaTextWidget,
VanillaNumberWidget,
...
} = VanillaWidgets;
const {
TextWidget,
NumberWidget,
...
} = AntdWidgets;
const {
MuiTextWidget,
MuiNumberWidget,
...
} = MuiWidgets;
const {
BootstrapTextWidget,
BootstrapNumberWidget,
...
} = BootstrapWidgets;
const {
FluentUITextWidget,
FluentUINumberWidget,
...
} = FluentUIWidgets;
```
--------------------------------
### Import Utils
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/README.md
Utilities for converting data from various formats back into the query builder's internal state.
```APIDOC
## loadFromJsonLogic
### Description
Convert query value from [JsonLogic](http://jsonlogic.com) format to internal Immutable format.
### Method
`Utils.Import.loadFromJsonLogic (jsonLogicObject, config) -> Immutable`
```
```APIDOC
## _loadFromJsonLogic
### Description
Internal method to convert query value from [JsonLogic](http://jsonlogic.com) format to internal Immutable format, returning errors.
### Method
`Utils.Import._loadFromJsonLogic (jsonLogicObject, config) -> [Immutable, errors]`
```
```APIDOC
## loadFromSpel
### Description
Convert query value from [Spring Expression Language (SpEL)](https://docs.spring.io/spring-framework/docs/3.2.x/spring-framework-reference/html/expressions.html) format to internal Immutable format.
### Method
`Utils.Import.loadFromSpel (string, config) -> [Immutable, errors]`
```
```APIDOC
## loadFromSql
### Description
Convert query value from SQL format to internal Immutable format. Requires import of `@react-awesome-query-builder/sql`.
### Method
`SqlUtils.loadFromSql (string, config) -> {tree: Immutable, errors: string[]}`
### Dependencies
`import { SqlUtils } from "@react-awesome-query-builder/sql"`
```
--------------------------------
### Load SQL Configuration
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/README.md
Convert query value from SQL format to internal Immutable format. Requires importing SqlUtils from @react-awesome-query-builder/sql.
```javascript
import { SqlUtils } from "@react-awesome-query-builder/sql"
SqlUtils.loadFromSql (string, config) -> {tree: Immutable, errors: string[]}
```
--------------------------------
### Defining Fields with Contextual Validation
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/CONFIG.adoc
Shows how to define fields and reference custom validation functions from the context. The `zipConfig` is used for JSON serialization.
```javascript
import {BasicConfig} from '@react-awesome-query-builder/ui';
const fields = {
firstName: {
type: "text",
fieldSettings: {
// use function `validateFirstName` from `ctx` by name
validateValue: "validateFirstName",
}
},
};
const ctx = {
...BasicConfig.ctx,
validateFirstName: (val: string) => {
return (val.length < 10);
},
};
// `zipConfig` can be passed to backend as JSON
const zipConfig = {
fields,
settings: {
useConfigCompress: true, // this is required to use Utils.ConfigUtils.decompressConfig()
},
// you can add here other sections like `widgets` or `types`, but don't add `ctx`
};
// Config can be loaded from backend with providing `ctx`
const config = Utils.ConfigUtils.decompressConfig(zipConfig, BasicConfig, ctx);
```
--------------------------------
### Import MUI Query Builder Components
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/packages/mui/README.md
Import necessary components and configurations from the MUI package for use in your React application. This includes type definitions, core query builder components, MUI specific configurations, and styles.
```javascript
import type { JsonGroup, Config, ImmutableTree, BuilderProps } from '@react-awesome-query-builder/mui'; // for TS example
import { Query, Builder, Utils as QbUtils } from '@react-awesome-query-builder/mui';
import { MuiConfig, MuiWidgets } from '@react-awesome-query-builder/mui';
import '@react-awesome-query-builder/mui/css/styles.css';
const InitialConfig = MuiConfig;
```
--------------------------------
### Date and Time Formatting Options
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/CONFIG.adoc
Settings for 'time', 'date', and 'datetime' widgets to control the display format, including 12-hour format with AM/PM.
```javascript
timeFormat: 'HH:mm'
```
```javascript
dateFormat: 'DD.MM.YYYY'
```
```javascript
use12Hours: false
```
--------------------------------
### Generate CSS Variables from Theme Library
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/CONFIG.adoc
Adapt the query builder's styling to the used UI framework's theme (MUI/AntDesign, etc.). Set to false to use static styles from versions prior to 6.7.0.
```javascript
designSettings.generateCssVarsFromThemeLibrary: true
```
--------------------------------
### Update Imports for v6.0.0
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/README.md
Change import paths from the main package to specific UI framework packages. Ensure all types and values are imported from a single package.
```diff
- import { Utils, Export, Import, BasicFuncs } from 'react-awesome-query-builder';
+ import { Utils, Export, Import, BasicFuncs } from '@react-awesome-query-builder/ui';
```
```diff
- import { Query, Builder, BasicConfig, Widgets, Operators } from 'react-awesome-query-builder';
+ import { Query, Builder, BasicConfig, VanillaWidgets, CustomOperators } from '@react-awesome-query-builder/ui';
```
```diff
- import AntdConfig from 'react-awesome-query-builder/lib/config/antd';
+ import {AntdConfig} from '@react-awesome-query-builder/antd';
```
```diff
- import MuiConfig from 'react-awesome-query-builder/lib/config/mui';
+ import {MuiConfig} from '@react-awesome-query-builder/mui';
```
```diff
- import MaterialConfig from 'react-awesome-query-builder/lib/config/material';
+ import {MaterialConfig} from '@react-awesome-query-builder/material';
```
```diff
- import BootstrapConfig from 'react-awesome-query-builder/lib/config/bootstrap';
+ import {BootstrapConfig} from '@react-awesome-query-builder/bootstrap';
```
```diff
- import 'react-awesome-query-builder/lib/css/styles.css';
+ import '@react-awesome-query-builder/ui/css/styles.css';
```
```diff
- import 'react-awesome-query-builder/lib/css/compact_styles.css';
+ import '@react-awesome-query-builder/ui/css/compact_styles.css'; // instead of styles.css for more compact look
```
--------------------------------
### Enable Ant Design v4 Styles
Source: https://github.com/ukrbublik/react-awesome-query-builder/blob/master/packages/examples/README.md
To test with Ant Design v4, uncomment the provided lines in `src/skins/lazyStyles/antd.tsx` to load the Ant Design CSS. This involves importing and using the CSS module.
```js
//import antd from "antd/dist/antd.css";
...
//(antd as LazyStyleModule).use();
...
//(antd as LazyStyleModule).unuse();
```