Custom Field in React Query Builder

147 views Asked by At

I am playing with an example taken from the docs and trying to create a custom field which shows an additional textbox and adds it to the built query.

import { useState } from 'react';
import type { Field, RuleGroupType } from 'react-querybuilder';
import { QueryBuilder, formatQuery } from 'react-querybuilder';
import './styles.scss';

const fields: Field[] = [
  { name: 'firstName', label: 'First Name'},
  { name: 'lastName', label: 'Last Name' },
  {
    name: 'groupedField1',
    label: 'Grouped Field 1',
    comparator: 'groupNumber',
    groupNumber: 'group1',
    valueSources: ['field', 'value'],
  },
];

const initialQuery: RuleGroupType = {
  combinator: 'and',
  rules: [
    { field: 'firstName', operator: 'beginsWith', value: 'Stev' },
    { field: 'lastName', operator: 'in', value: 'Vai,Vaughan' },
    {
      field: "groupedField1",
      value: "groupedField1",
      operator: "=",
      valueSource: "field"
    },
  ],
};

export const App = () => {
  const [query, setQuery] = useState(initialQuery);

  return (
    <div>
      <QueryBuilder fields={fields} query={query} onQueryChange={setQuery} />

      <h4>Query</h4>
      <pre>
        <code>{formatQuery(query, 'json')}</code>
      </pre>
    </div>
  );
};

My use case is, if the chosen field is a JSON field, I want to be able get sub-fields given a path. Concretely, if the field name chosen from the drop down includes string "JSON", I want to display an additional textbox, where the user can enter a JSON query similar to JSONB querying in PSQL such as 'sub_obj_1->sub_obj_2'. I expect the resulting query to have the additional field 'path' like

{
  "field": "some json field",
  "path": "sub_obj_1->sub_obj_2",
  "operator": "=",
  "value": "val",
  "id": "268026e1-072b-4f64-8de4-8ebbbcb0a3f6"
},

How can I implement such a custom field?

0

There are 0 answers