Fields and operators
Enhancing the query builder with fields from the sample sales data set
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
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
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.
There are two ways to configure operators in React Query Builder:
getOperatorsprop at query level
operatorsattribute 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
Create a new file called
getOperators.ts in the
The date fields in our data set,
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
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.