Security News
Weekly Downloads Now Available in npm Package Search Results
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.
react-querybuilder
Advanced tools
The Query Builder component for React
React Query Builder is a fully customizable query builder component for React, along with a collection of utility functions for importing from, and exporting to, various query languages like SQL, MongoDB, and more.
Complete documentation is available at https://react-querybuilder.js.org.
Click here to see a live, interactive demo.
Custom components are not limited to the following libraries, but these have first-class support through their respective compatibility packages:
npm i react-querybuilder
# OR yarn add / pnpm add / bun add
import { useState } from 'react';
import { Field, 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' },
{ name: 'age', label: 'Age', inputType: 'number' },
{ name: 'address', label: 'Address' },
{ name: 'phone', label: 'Phone' },
{ name: 'email', label: 'Email', validator: ({ value }) => /^[^@]+@[^@]+/.test(value) },
{ name: 'twitter', label: 'Twitter' },
{ name: 'isDev', label: 'Is a Developer?', valueEditorType: 'checkbox', defaultValue: false },
];
const initialQuery: RuleGroupType = {
combinator: 'and',
rules: [],
};
export const App = () => {
const [query, setQuery] = useState(initialQuery);
return <QueryBuilder fields={fields} query={query} onQueryChange={setQuery} />;
};
To enable drag-and-drop, install the @react-querybuilder/dnd
package and nest <QueryBuilder />
under <QueryBuilderDnD />
.
To export queries as SQL, MongoDB, or one of several other formats, use the formatQuery
function.
const query = {
combinator: 'and',
rules: [
{
field: 'first_name',
operator: 'beginsWith',
value: 'Stev',
},
{
field: 'last_name',
operator: 'in',
value: 'Vai, Vaughan',
},
],
};
const sqlWhere = formatQuery(query, 'sql');
console.log(sqlWhere);
// `(first_name like 'Stev%' and last_name in ('Vai', 'Vaughan'))`
To import queries use parseSQL
, parseMongoDB
, parseJsonLogic
, parseCEL
, or parseSpEL
depending on the source.
Tip: parseSQL
will accept a full SELECT
statement or the WHERE
clause by itself (everything but the expressions in the WHERE
clause will be ignored). Trailing semicolon is optional.
const query = parseSQL(
`SELECT * FROM my_table WHERE first_name LIKE 'Stev%' AND last_name in ('Vai', 'Vaughan')`
);
console.log(query);
/*
{
"combinator": "and",
"rules": [
{
"field": "first_name",
"operator": "beginsWith",
"value": "Stev",
},
{
"field": "last_name",
"operator": "in",
"value": "Vai, Vaughan",
},
],
}
*/
formatQuery
, transformQuery
, and the parse*
functions can be used without importing from react
(on the server, for example) like this:
import { formatQuery } from 'react-querybuilder/formatQuery';
import { parseCEL } from 'react-querybuilder/parseCEL';
import { parseJsonLogic } from 'react-querybuilder/parseJsonLogic';
import { parseMongoDB } from 'react-querybuilder/parseMongoDB';
import { parseSpEL } from 'react-querybuilder/parseSpEL';
import { parseSQL } from 'react-querybuilder/parseSQL';
import { transformQuery } from 'react-querybuilder/transformQuery';
(As of version 7, the parse*
functions are only available through these extended exports.)
[v7.0.0] - 2024-03-06
react-redux
v9 dependency.import
requirement |
| ---------------- | -------------------------------------------------------------------- |
| parseCEL
| import { parseCEL } from "react-querybuilder/parseCEL"
|
| parseJsonLogic
| import { parseJsonLogic } from "react-querybuilder/parseJsonLogic"
|
| parseMongoDB
| import { parseMongoDB } from "react-querybuilder/parseMongoDB"
|
| parseSQL
| import { parseSQL } from "react-querybuilder/parseSQL"
|translations.addRule.label
| "+Rule"
| "+ Rule"
| Space added between "+" and "Rule" |
| translations.addGroup.label
| "+Group"
| "+ Group"
| Space added between "+" and "Group" |
| translations.removeRule.label
| "x"
| "⨯"
| HTML entity ✗
/ ⨯
|
| translations.removeGroup.label
| "x"
| "⨯"
| HTML entity ✗
/ ⨯
|independentCombinators
prop has been deprecated and will be ignored if used. To enable the independent combinators functionality, use RuleGroupTypeIC
for the query
or defaultQuery
prop. The query builder will detect the query type and behave accordingly. If the independentCombinators
prop is present, a warning will be logged to the console (in "development" mode only).parseMongoDB
now generates more concise queries when it encounters $not
operators that specify a single, boolean condition. Whereas previously that would yield a group with not: true
, it will now generate a rule with a inverted/negated operator ("="
inverted is "!="
, "contains"
inverted is "doesNotContain"
, etc.). To prevent this behavior, set the preventOperatorNegation
option to true
([#653]).disabled
prop has been un-deprecated. Disabling the entire query with the prop and setting disabled: true
as a property of the root group now produce different behaviors. Specifically, the root group's lock/unlock button will always be enabled if the disabled
prop is not true
.extraProps
prop that will be passed directly to the library component, spread like {...extraProps}
. The type of extraProps
is any
because each value editor can render one of several library components that accept different props."json_without_ids"
export format now explicitly removes the id
and path
properties from the output, leaving all other properties unchanged. Previously this format would only include specific properties which had the effect of removing any non-standard properties.ValueEditorProps
, ValueSelectorProps
, and FieldSelectorProps
must extend the new FullOption
interface instead of Option
.lock*
, clone*
, remove*
, and dragHandle
) with SVGs from official icon packages. This brings them more in line with their respective design systems by default.
@react-querybuilder/antd
: @ant-design/icons
@react-querybuilder/bootstrap
: bootstrap-icons
@react-querybuilder/chakra
: @chakra-ui/icons
@react-querybuilder/fluent
: @fluentui/react-icons-mdl2
@react-querybuilder/material
: @mui/icons-material
@react-querybuilder/mantine
now requires Mantine v7.@react-querybuilder/bootstrap
component BootstrapDragHandle
has been removed. It is redundant since dragHandle.label
can now be a ReactNode
.useQueryBuilder
hook has been split into useQueryBuilderSetup
and useQueryBuilderSchema
. Each hook takes the full QueryBuilder
props object as its first parameter (as useQueryBuilder
did), and useQueryBuilderSchema
accepts the return value of useQueryBuilderSetup
as its second parameter.useStopEventPropagation
hook now takes a single function as its parameter instead of an object map of functions, so it must be run for each wrapped function individually.Path
instead of number[]
. The actual type is the same: type Path = number[]
.RuleGroupTypeIC
type now includes combinator?: undefined
to ensure that query objects intended for use in query builders where independentCombinators
is enabled do not contain combinator
properties.parseFloat
was used internally, parseNumber
is now used. parseNumber
now delegates parsing to the more versatile numeric-quantity
package. The default behavior has not changed, but a new "enhanced" option will ignore trailing invalid characters (e.g., "abc" in "123abc") just like the native parseFloat
method, with the only difference being it won't return NaN
when parsing fails. Additionally, the numericRegex
export is now adapted from (but largely identical to) the export of the same name from numeric-quantity
.valueEditorType
over the getValueEditorType
prop has moved from the useRule
hook to the useQueryBuilderSetup
hook.query-builder-layout.css
/query-builder-layout.scss
. The default stylesheet, query-builder.css
/query-builder.scss
, still contains structural styles but also includes more decorative styles like colors and border styles. The effective styles of the default stylesheet have not changed from version 6.value
as the identifier property in lieu of name
. Additionally, all Option
s within OptionList
s passed down to subcomponents (fields
, fieldData
, combinators
, operators
, values
, etc.) are guaranteed to have both name
and value
. This makes it easier to use libraries like react-select
that expect a list of type { value: string; label: string; }[]
and not { name: string; label: string; }[]
.
name
/value
properties) will now be inferred from the fields
prop if they have been narrowed from string
. These narrowed types will be applied to subcomponents and other props that take fields or field identifiers as arguments/props.Field
, Operator
, and Combinator
interfaces each have corresponding Full*
and *ByValue
counterparts. Both name
and value
are required in the Full*
interfaces; only value
is required in the *ByValue
interfaces.controlElements
prop: actionElement
and valueSelector
. When actionElement
is defined, it will be used for each component that defaults to ActionElement
(as long as that component is not explicitly overridden in the controlElements
prop). Same for valueSelector
and components that default to ValueSelector
(including ValueEditor
in cases where it renders a value selector). This makes it possible to define replacement components for all buttons and selectors at once instead of one-by-one.
<!-- prettier-ignore -->
| controlElements
property | Sets default for |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| valueSelector
| combinatorSelector
, fieldSelector
, operatorSelector
, valueSourceSelector
, valueEditor
(when rendering a value selector) |
| actionElement
| addGroupAction
, addRuleAction
, cloneGroupAction
, cloneRuleAction
, lockGroupAction
, lockRuleAction
, removeGroupAction
, removeRuleAction
|showShiftActions
prop provides first-class support for rearranging rules within a query without enabling drag-and-drop. When showShiftActions
is true
, two buttons will appear at the front of each rule and group (except the root group), stacked vertically by default. The first/upper button will shift the rule or group one spot higher, while the second/lower button will shift it one spot lower. Pressing the modifier key (Alt
on Windows/Linux, Option
/⌥
on Mac) while clicking a shift action will clone the rule or group instead of just moving it. A ShiftActions
component has been added, along with a corresponding component for each compatibility package. New translations
properties shiftActionUp
and shiftActionDown
allow configuration of the label and title of each button within the new component.title
attribute to the outermost <div>
of each rule group. The text of this attribute can be customized with the accessibleDescriptionGenerator
function prop.context
prop, but that workaround is no longer necessary.) The first two methods are available from the schema
prop passed to every component, and should only be used in event handlers. The third is a React Hook and should follow the appropriate rules.
getQuery()
: returns the current root query object.dispatchQuery(query)
: updates the internal query state and then calls the onQueryChange
callback.useQueryBuilderSelector(selector)
: returns the current root query object using the provided selector function, which can be generated with getQuerySelectorById(props.schema.qbId)
.get*
callback props now receive an additional "meta" parameter with a fieldData
property (more properties may be added to the "meta" object in the future). fieldData
is the full Field
object from the fields
array for the given field
name, including any custom properties (a common one is datatype
). This eliminates the need to find the field object based solely on the field's name
within the get*
functions themselves. The following callback props provide the new "meta" parameter: getDefaultOperator
, getDefaultValue
, getInputType
, getOperators
, getRuleClassname
, getValueEditorSeparator
, getValueEditorType
, getValues
, and getValueSources
.<QueryBuilderDnD />
and <QueryBuilderDndWithoutProvider />
from @react-querybuilder/dnd
now accept a canDrop
callback prop. If provided, the function will be called when dragging a rule or group. The only parameter will be an object containing dragging
and hovering
properties, representing the rule/group being dragged and the rule/group over which it is hovered, respectively. The objects will also contain the path
of each item. If canDrop
returns false
, dropping the item at its current position will have no effect on the query. Otherwise the normal drag-and-drop rules will apply.label
props and translations.*.label
properties now accept ReactNode
. This includes all action elements (buttons), "not" toggles, and drag handles. Previously label
was limited to string
. This enables, for example, the assignment of SVG elements as labels.translations
prop can now be passed down through the compatibility context providers like <QueryBuilderBootstrap />
and <QueryBuilderMaterial />
. The object will be merged with the translations
prop of descendant QueryBuilder
components.formatQuery
now receive the full Field
object in the options parameter, as long as the fields
array is provided alongside ruleProcessor
. In TypeScript, the member type of the fields
array now requires a label: string
property. Previously, only name
was required.parseMongoDB
now supports custom operators through the additionalOperators
option.uniqByIdentifier
replaces uniqByName
, which has been deprecated. uniqByIdentifier
will remove duplicates based on the value
property, or name
if value
is undefined (see [#586]).formatQuery
.@react-querybuilder/tremor
.disabled
property of individual options in option lists.format
option set during a call to formatQuery
will be passed to custom rule processors as a property of the options object in the second parameter.parseSpEL
method for importing SpEL expressions.query
has a stable reference. The most common violation of that rule is probably inline arrow function declarations in the onQueryChange
prop, a problem which can usually be addressed with useCallback
.MantineValueSelector
now correctly renders option group headers.useEffect
call from usePrevious
and a ref that tracked "first render" from useQueryBuilderSchema
.valueEditorType
evaluates to "multiselect"
.useEffect
calls.formatQuery
for "jsonlogic" will no longer collapse subgroups that only contain one rule into a single JsonLogic rule. Full query objects that contain only one rule will still be collapsed.values
list is defined for a field, and the value is reset due to resetOnFieldChange
or resetOnOperatorChange
being true
, the rule value
will no longer be set to the first value in the list unless the valueEditorType
evaluates to "select" or "radio".formatQuery
now renders the fallback expression for subgroups where all rules are invalid. Previously this could result in "()"
, which is invalid SQL.FAQs
The React <QueryBuilder /> component for constructing queries
The npm package react-querybuilder receives a total of 60,582 weekly downloads. As such, react-querybuilder popularity was classified as popular.
We found that react-querybuilder demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.
Security News
A Stanford study reveals 9.5% of engineers contribute almost nothing, costing tech $90B annually, with remote work fueling the rise of "ghost engineers."
Research
Security News
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.