React Query Builder

website·Indexed 29 days ago

https://react-querybuilder.js.org/

A React component for building complex queries with a hierarchical structure. It features a flexible API for managing fields, operators, and combinators, with support for exporting queries to formats like SQL, MongoDB, JsonLogic, CEL, and JSONata. The library includes advanced capabilities such as a rules engine, expression building with drag-and-drop support, date/time features, and compatibility packages for frameworks like MUI and shadcn.

Tokens
73.8K
Snippets
352
Records
448
Agent score
66%

What's inside React Query Builder

  1. Implement custom action elements and query properties

    React Query Builder allows replacing default components to implement custom logic:

    • Multiple Action Elements: You can replace the default addRuleAction with a custom component. Use props.schema.getQuery() to get the current state and props.schema.dispatchQuery() to update the query with specific pre-selected fields.
    • Custom Query Properties: You can add non-standard properties (e.g., caseSensitive) to the query hierarchy and manage them via custom controls (like checkboxes) in the UI. These properties can then be handled by a custom rule processor during export (e.g., using formatQuery to wrap fields in SQL LOWER() functions).
  2. Manage query state with QueryManager

    The QueryManager class is a stateful wrapper for managing query state, mutations, and validation. It provides a centralized way to handle rules and groups while maintaining undo/redo history and configuration. By default, all objects returned by the manager (query, field list, etc.) are deep-frozen to ensure immutability, though this can be disabled for compatibility with proxy-based frameworks.
    const q = new QueryManager(query, { fields, freeze: false });
  3. Use ShiftActions to reorder rules and groups

    The ShiftActions component provides 'Up' and 'Down' buttons to move a rule or subgroup within the query hierarchy. These buttons appear at the front of each rule and subgroup when the showShiftActions prop is set to true on the Query Builder.

    • Up button: Moves the rule/group above the preceding rule or into the preceding group as the last member.
    • Down button: Moves the rule/group below the next rule or into the next group as the first member.

    Note: If a subgroup immediately follows a rule, shifting that rule down will move it into the subgroup as the first element.

  4. Use @react-querybuilder/core for framework-agnostic logic

    @react-querybuilder/core provides the core logic for query derivation (precedence rules for fields, operators, values, class names, and history) without a React dependency. This allows developers to build equivalent UIs in other frameworks like Solid, Svelte, or Vue by calling these functions directly.
  5. Understand default drag-and-drop styling in React Query Builder

    The default stylesheet for React Query Builder includes specific styles that are applied during drag-and-drop operations. These styles are designed to provide visual feedback to the user, helping them anticipate where a rule or group will be placed upon dropping.
  6. Use the InlineCombinator component

    The InlineCombinator component wraps a combinatorSelector (which defaults to ValueSelector if the component prop is not provided) inside a <div class="betweenRules inline-combinator"> container. This component is automatically utilized when showCombinatorsBetweenRules is enabled or when the query configuration uses independent combinators.
  7. Understand and use the query path concept

    React Query Builder uses a path (an integer array) to uniquely identify the structural position of rules and groups within a query hierarchy. This is distinct from the id property, which identifies the object but not its position.

    • The root query group always has a path of [].
    • Nested rules and groups have paths based on their index within their parent's rules array.
    • Calculation: path = [...parentPath, index].

    For example, a rule at index 0 of the root group has path [0]. A rule at index 0 inside a group that is itself at index 1 of the root group has path [1, 0].

    // Example query structure and corresponding paths
    const query: RuleGroupType = {
      combinator: 'and',
      rules: [
        // path: [0]
        { field: 'f1', operator: '=', value: 'v1' },
        // path: [1]
        {
          combinator: 'or',
          rules: [
            // path: [1, 0]
            { field: 'f2', operator: '=', value: 'v2' },
            // path: [1, 1]
            { field: 'f3', operator: '=', value: 'v3' },
          ],
        },
      ],
    };
  8. React Query Builder Ecosystem and Feature Integration

    React Query Builder provides a modular ecosystem of packages and integrations:

    • UI Style Packs: Supports Ant Design, Bootstrap, Bulma, Chakra UI, Fluent UI, Mantine, MUI/Material, PrimeReact, and Tremor.
    • Platform Support: Official React Native support via @react-querybuilder/native.
    • Advanced Features:
      • Drag-and-drop via @react-querybuilder/dnd.
      • Relative dates and dialect-specific formatting via @react-querybuilder/datetime.
      • Expression support via @react-querybuilder/expr.
      • Rules engine via @react-querybuilder/rules-engine.
    • Developer Experience: Built-in ARIA attributes for accessibility, translations prop for i18n, and per-field validator functions for data validation.
  9. Understand the React Query Builder function architecture

    Functions in React Query Builder are split into two distinct concerns to keep the UI and validator decoupled from serialization logic:

    1. Metadata (ExpressionFunctionMeta): Defines the UI label and arity (number of arguments). This drives the expression editor and format-agnostic validator. It is passed to the QueryBuilderExpressions component via the functions prop.
    2. Serializers: Define how a function is rendered in a specific export format (e.g., SQL, JSONLogic). Each export format has its own registry (e.g., SQLSerializerRegistry).
  10. Use React Query Builder with non-React frameworks

    React Query Builder is not limited to React. Official ports for other frameworks are available, utilizing framework-agnostic derivations from @react-querybuilder/core. These ports maintain identical query shapes, import/export utilities, and configuration options (such as fields and operators), while providing a component API idiomatic to the target framework.
  11. Use QueryManager for programmatic query management

    QueryManager is a stateful wrapper around query tools that allows developers to build, modify, validate, and format queries programmatically. Because it has no React dependency, it can be used in server-side environments, CLIs, or any non-UI context. It supports method chaining by returning the manager instance after mutations.
    import { QueryManager } from 'react-querybuilder';
    
    // Initialize with fields configuration
    const q = new QueryManager(undefined, { fields });
    
    // Chain mutations to build the query
    q.add({ field: 'firstName', operator: '=', value: 'Steve' })
      .add({ field: 'lastName', operator: '=', value: 'Vai' })
      .update('operator', 'contains', 'rule-id-1');
    
    // Perform actions
    const isValid = q.validate(); // returns boolean | ValidationMap
    const sql = q.format('sql');   // returns string
    const query = q.getQuery();    // returns RuleGroupType
  12. Programmatically manage query objects

    React Query Builder provides utilities to build and modify query objects programmatically. This allows developers to manipulate the query state (adding, removing, or updating rules and groups) without relying on the <QueryBuilder /> UI component.