How can we implement autocomplete with API and multi-select in react-querybuilder?

298 Views Asked by At

I am building a search query builder with react-querybuilder and want to fetch the values of certain rules from an API. I also want the values field to be a filter and not just a dropdown, where users can input their filter string and results will appear in the dropdown. If we can make the results as multi-select then it would be better like shown in the image added. (https://i.stack.imgur.com/8tMHF.png) I researched on the react-querybuilder and found that it doesn't have the functionality that I'm trying to make. If anyone from the community can help, please reach out. Thanks

1

There are 1 best solutions below

7
Jake Boone On BEST ANSWER

Maintainer of React Query Builder here. You can achieve this with a custom value editor. The best documentation I have on custom components right now is here. That walks you through creating a custom value editor for dates using react-datepicker, but the concept would be the same for any other React library.

There are no built-in data fetching features in RQB, so you'd need to build that on your own or use a library, but I would recommend react-select for its multiselect and async features.

The RQB home page actually has a multi-select example using react-select. The code for the component itself is here (simplified for brevity below), and usage is here.

const ExtendedValueEditor_Select = (props: ValueEditorProps) => {
  return (
    <Select
      value={props.value}
      isMulti
      onChange={v => props.handleOnChange(v)}
      options={selectOptions}
    />
  );
};

Notes:

  • selectOptions is an array of type { value: string; label: string; }[].
  • This is almost certainly not the entire value editor you want—please see the "fallback" docs I mentioned earlier.

To use the component, assign it to valueEditor in the controlElements prop.

<QueryBuilder
  fields={selectFields}
  controlElements={{ valueEditor: ExtendedValueEditor_Select }}
/>

Feel free to file issues/discussions on GitHub or join the Discord chat if you have other questions about React Query Builder.