Fields and operators

Enhancing the query builder with fields from the sample sales data set

Fields#

Now we'll add fields from the sample sales data set. This is a randomized data set with columns for location, item type, dates, quantities and totals. Each field will need name and label attributes. We'll come back to that later and augment the field names and labels with some other attributes to configure the behavior of the query builder in a later lesson.

Let's split this out into a separate file, fields.ts, because it can get quite large. Create a new file called fields.ts in the client/src/ folder.

Make sure you include them in the query builder props in App.tsx by changing the fields assignment and adding the following import:

View the application and check that all the new fields are available to choose from the drop-down list.

We have a working query builder now, but all the fields have the same options (meaning the operators and value editors are the defaults). What we really want to do is tailor the operators and value editors to each specific field so that users get an optimal experience.

Operators#

There are two ways to configure operators in React Query Builder:

  • the getOperators prop at query level

  • the operators attribute at field level

We're going to use the getOperators method in order to keep all our operator configuration in the same place. To configure the operators with the getOperators prop, we will again split this out into a separate file to keep things nice and tidy in our App.tsx file.

Create a new file called getOperators.ts in the client/src/ folder.

The date fields in our data set, order_date and ship_date, will get date-related operators ("is before", "is after", etc), while numeric fields will get number-related operators ("is greater than", "is less than", etc). The remaining fields will get the default operators, which we can import from react-querybuilder.

And once again, include the new function in the query builder props.

View the application and make sure the correct operators are available when you choose specific fields.

Let's take a look at the App.tsx file as it stands now.

Start a new discussion. All notification go to the author.