react-querybuilder

The React <QueryBuilder /> component for constructing queries

Usage no npm install needed!

<script type="module">
  import reactQuerybuilder from 'https://cdn.skypack.dev/react-querybuilder';
</script>

README

react-querybuilder

The Query Builder component for React

Screenshot

Documentation

Complete documentation is available at react-querybuilder.js.org.

Demo

Click here to see a live, interactive demo.

To run the demo yourself...
  1. Clone this repo
  2. yarn Install dependencies
  3. yarn start Run a local server
  4. Visit http://localhost:8080 in your browser

To use the official compatibility components as seen in the demo (select options from the Style dropdown), take a look at the packages under the @react-querybuilder org on npmjs.com. We currently support:

Basic usage

npm install react-querybuilder --save
# OR
yarn add react-querybuilder
import { useState } from 'react';
import QueryBuilder, { RuleGroupType } from 'react-querybuilder';
import 'react-querybuilder/dist/query-builder.css';

const fields = [
  { 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 },
];

export const App = () => {
  const [query, setQuery] = useState<RuleGroupType>({
    combinator: 'and',
    rules: [],
  });

  return <QueryBuilder fields={fields} query={query} onQueryChange={q => setQuery(q)} />;
};

Export/import

To export queries as SQL, MongoDB, or other formats, use the formatQuery function.

const query = {
  combinator: 'and',
  rules: [
    {
      field: 'first_name',
      operator: 'beginsWith',
      value: 'Steve',
    },
    {
      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 from SQL, use parseSQL. You can pass a full SELECT statement or the WHERE clause by itself.

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": "Steve",
    },
    {
      "field": "last_name",
      "operator": "in",
      "value": "Vai, Vaughan",
    },
  ],
}
*/

Note: formatQuery and parseSQL can be used without importing React (for example, on the server) like this:

import { formatQuery } from 'react-querybuilder/dist/formatQuery';
import { parseSQL } from 'react-querybuilder/dist/parseSQL';