Getting started
TL;DR
Installation
To install react-querybuilder
, use a package manager like npm, Yarn, pnpm, or Bun, or follow these instructions for a buildless environment.
- npm
- Bun
- Yarn
- pnpm
npm i react-querybuilder
bun add react-querybuilder
yarn add react-querybuilder
pnpm add react-querybuilder
Basics
The simplest way to create a query builder is to render the QueryBuilder
component with no props. (Be sure to import the official stylesheet, which is available in .css
and .scss
flavors.)
Functional, but not very useful. To really get value out of the query builder, we'll first need to define a set of fields for the user to choose from. We can pass the fields
array into the query builder through the fields
prop.
In the query builder below, click the "+ Rule" button and then the field selector to see the field choices.
Much more useful, but you probably want to monitor and control what users do with the query builder. Let's set up a state variable using the React Hook useState
. This will store our query object and allow us to pass it on to other components, event handlers, etc.
The state variable query
will be passed to the query
prop, and the setter method setQuery
will be used in the onQueryChange
callback. Let's also seed the query object with a couple of rules, making sure that the field
property of each rule matches the name
property of one of our fields.
Non-TypeScript version
import { useState } from 'react';
import { QueryBuilder } from 'react-querybuilder';
import 'react-querybuilder/dist/query-builder.css';
const fields = [
{ name: 'firstName', label: 'First Name' },
{ name: 'lastName', label: 'Last Name' },
];
export default () => {
const [query, setQuery] = useState({
combinator: 'and',
rules: [
{ field: 'firstName', operator: '=', value: 'Steve' },
{ field: 'lastName', operator: '=', value: 'Vai' },
],
});
return <QueryBuilder fields={fields} query={query} onQueryChange={setQuery} />;
};
Exporting queries
To convert a query object into other formats like SQL, MongoDB, and CEL, you can use the formatQuery
function (full documentation). The example below demonstrates the conversion of a query to its equivalent SQL form. Modify the query by manipulating the form elements and the SQL will update accordingly.
Onward and upward!
To discover all the options of React Query Builder, start with the main component documentation. To play around with various configurations, including other export/import formats, check out the demo.
Training
For an extended tutorial on configuration and customization of react-querybuilder
, including information about integrating it with a backend API and advanced reporting components (grids, maps, charts, etc.), check out the course Building Advanced Admin Reporting in React, taught by this library's maintainer, over at newline.