Skip to main content
Beta FeatureThis feature is currently in beta, and needs to be imported from @servicetitan/anvil2/beta.While we hope to minimize breaking changes, they may occur due to feedback we receive or other improvements. These will always be documented in the changelog and communicated in Slack.Please reach out in the #ask-designsystem channel with any questions or feedback!

Overview

The multi-select field family includes two components for different use cases:
  • MultiSelectField — For async data loading with support for pagination (page-based, offset-based, or group-based lazy loading)
    • Includes automatic debouncing of the search input (configurable via the debounceMs prop)
    • Includes automatic caching of the search input (configurable via the cache prop)
  • MultiSelectFieldSync — For client-side filtering of static option arrays
Both components provide a searchable dropdown interface for selecting multiple options, displaying selected values as chips with adaptive display modes (popover or dialog).

MultiSelectFieldSync (Static Options)

Use MultiSelectFieldSync when you have a static list of options that can be filtered client-side.
import { useState } from "react";
import { MultiSelectFieldSync } from "@servicetitan/anvil2/beta";

const options = [
  { id: 1, label: "Option One" },
  { id: 2, label: "Option Two" },
  { id: 3, label: "Option Three" },
];

const ExampleComponent = () => {
  const [selectedOptions, setSelectedOptions] = useState([]);

  return (
    <MultiSelectFieldSync
      label="Select options"
      placeholder="Search options..."
      options={options}
      value={selectedOptions}
      onSelectedOptionsChange={setSelectedOptions}
    />
  );
};

Filtering and Sorting

By default, MultiSelectFieldSync uses match-sorter to filter options by their label and searchText fields. Results are also ranked by match quality, so the best matches appear first. Before any search is performed, options appear in the order they are supplied. You can customize this behavior in two ways:

Using match-sorter options

Pass a match-sorter options object to customize the default filtering and sorting behavior (e.g., change which keys are matched or adjust ranking):
<MultiSelectFieldSync
  options={options}
  filter={{ 
    keys: ["label", "searchText"], 
    // ...other match-sorter options
  }}
  // ...other props
/>

Using a custom filter function

Pass a function for full control over both filtering and sort order. The returned array determines the exact order options appear in the dropdown:
<MultiSelectFieldSync
  options={options}
  filter={(options, searchValue) => {
    return options.filter((option) =>
      option.label?.toLowerCase().includes(searchValue.toLowerCase())
    );
  }}
  // ...other props
/>

MultiSelectField (Async Loading)

Use MultiSelectField when options need to be fetched from an API or when dealing with large datasets that require server-side filtering.

Basic Usage

import { useState } from "react";
import { MultiSelectField } from "@servicetitan/anvil2/beta";

const ExampleComponent = () => {
  const [selectedOptions, setSelectedOptions] = useState([]);

  return (
    <MultiSelectField
      label="Select Tags"
      placeholder="Search tags..."
      loadOptions={async (searchValue) => {
        const response = await fetch(`/api/tags?q=${searchValue}`);
        const tags = await response.json();
        return tags.map((tag) => ({
          id: tag.id,
          label: tag.name,
        }));
      }}
      value={selectedOptions}
      onSelectedOptionsChange={setSelectedOptions}
    />
  );
};

Lazy Loading Modes

MultiSelectField supports three lazy loading modes for paginated data:

Page-based Pagination

<MultiSelectField
  lazy="page"
  lazyOptions={{ pageSize: 10 }}
  loadOptions={async (searchValue, pageNumber, pageSize) => {
    const response = await fetch(
      `/api/items?q=${searchValue}&page=${pageNumber}&size=${pageSize}`
    );
    const { data, totalCount } = await response.json();
    return {
      options: data.map((item) => ({ id: item.id, label: item.name })),
      hasMore: pageNumber * pageSize + data.length < totalCount,
    };
  }}
  // ...other props
/>

Offset-based Pagination

<MultiSelectField
  lazy="offset"
  lazyOptions={{ limit: 15 }}
  loadOptions={async (searchValue, offset, limit) => {
    const response = await fetch(
      `/api/items?q=${searchValue}&offset=${offset}&limit=${limit}`
    );
    const { data, totalCount } = await response.json();
    return {
      options: data.map((item) => ({ id: item.id, label: item.name })),
      hasMore: offset + limit < totalCount,
    };
  }}
  // ...other props
/>

Group-based Loading

For loading grouped options incrementally:
<MultiSelectField
  lazy="group"
  groupToString={(groupValue) => String(groupValue)}
  loadOptions={async (searchValue, previousGroupKey) => {
    const response = await fetch(
      `/api/items?q=${searchValue}&afterGroup=${previousGroupKey || ""}`
    );
    const { data, hasMore } = await response.json();
    return {
      options: data.map((item) => ({
        id: item.id,
        label: item.name,
        group: item.category, // Required for grouped options
      })),
      hasMore,
    };
  }}
  // ...other props
/>

Select All

Enable bulk selection with the selectAll prop.
Select All is shown only when the search input is empty.

MultiSelectField

With MultiSelectField, the parent component is responsible for handling the select/deselect logic via onClick and managing the checkState:
import { useState } from "react";
import { MultiSelectField } from "@servicetitan/anvil2/beta";

const allOptions = [
  { id: 1, label: "Option One" },
  { id: 2, label: "Option Two" },
  { id: 3, label: "Option Three" },
];

const ExampleComponent = () => {
  const [selectedOptions, setSelectedOptions] = useState([]);

  const handleSelectAll = () => {
    if (selectedOptions.length === allOptions.length) {
      setSelectedOptions([]);
    } else {
      setSelectedOptions(allOptions);
    }
  };

  return (
    <MultiSelectField
      label="Select Items"
      loadOptions={async () => allOptions}
      value={selectedOptions}
      onSelectedOptionsChange={setSelectedOptions}
      selectAll={{
        label: "Select All Items",
        onClick: handleSelectAll,
        checkState:
          selectedOptions.length === allOptions.length
            ? "checked"
            : selectedOptions.length > 0
              ? "indeterminate"
              : "unchecked",
      }}
    />
  );
};

MultiSelectFieldSync

MultiSelectFieldSync provides a simplified selectAll prop. Click handling and check state are managed automatically:
// Enable with default label
<MultiSelectFieldSync
  label="Select Tags"
  options={options}
  value={selectedOptions}
  onSelectedOptionsChange={setSelectedOptions}
  selectAll
/>

// Enable with custom label
<MultiSelectFieldSync
  label="Select Tags"
  options={options}
  value={selectedOptions}
  onSelectedOptionsChange={setSelectedOptions}
  selectAll={{ label: "Select All Tags" }}
/>

// Enable with dynamic label based on check state
<MultiSelectFieldSync
  label="Select Tags"
  options={options}
  value={selectedOptions}
  onSelectedOptionsChange={setSelectedOptions}
  selectAll={{ label: (checked) => checked ? "Deselect All" : "Select All" }}
/>

Select Filtered

Enable selection of options matching the current search term with the selectFiltered prop. Select All and Select Filtered are mutually exclusive: Select All is shown when the search input is empty, and Select Filtered is shown when a search term is active. The default label dynamically includes the search term (e.g., Select items matching "appl").

MultiSelectField

With MultiSelectField, provide a function that receives the current searchValue and returns a config object with onClick, checkState, and an optional label. Since the function receives the search value, you can use it to filter options and compute the checked state inline:
import { useState } from "react";
import { MultiSelectField } from "@servicetitan/anvil2/beta";

const allOptions = [
  { id: 1, label: "Apple" },
  { id: 2, label: "Apricot" },
  { id: 3, label: "Banana" },
  { id: 4, label: "Cherry" },
];

const filterBySearch = (searchValue: string) =>
  allOptions.filter((opt) =>
    opt.label.toLowerCase().includes(searchValue.toLowerCase()),
  );

const ExampleComponent = () => {
  const [selectedOptions, setSelectedOptions] = useState([]);
  const selectedIds = new Set(selectedOptions.map((o) => o.id));

  return (
    <MultiSelectField
      label="Fruits"
      loadOptions={async (searchValue) => filterBySearch(searchValue)}
      value={selectedOptions}
      onSelectedOptionsChange={setSelectedOptions}
      selectFiltered={(searchValue) => {
        const filtered = filterBySearch(searchValue);
        const allFilteredSelected =
          filtered.length > 0 &&
          filtered.every((o) => selectedIds.has(o.id));
        const someFilteredSelected = filtered.some((o) =>
          selectedIds.has(o.id),
        );
        return {
          onClick: () => {
            if (allFilteredSelected) {
              const filteredIds = new Set(filtered.map((o) => o.id));
              setSelectedOptions(
                selectedOptions.filter((o) => !filteredIds.has(o.id)),
              );
            } else {
              const merged = [...selectedOptions];
              for (const opt of filtered) {
                if (!selectedIds.has(opt.id)) merged.push(opt);
              }
              setSelectedOptions(merged);
            }
          },
          checkState: allFilteredSelected
            ? "checked"
            : someFilteredSelected
              ? "indeterminate"
              : "unchecked",
        };
      }}
    />
  );
};

MultiSelectFieldSync

MultiSelectFieldSync provides a simplified selectFiltered prop. Click handling and check state are managed automatically based on the filtered options and current selection:
// Enable with default dynamic label
<MultiSelectFieldSync
  label="Fruits"
  options={options}
  value={selectedOptions}
  onSelectedOptionsChange={setSelectedOptions}
  selectFiltered
/>

// Enable with custom label based on search value
<MultiSelectFieldSync
  label="Fruits"
  options={options}
  value={selectedOptions}
  onSelectedOptionsChange={setSelectedOptions}
  selectFiltered={(searchValue) => ({
    label: `Select items matching "${searchValue}"`,
  })}
/>

// Combine with selectAll for full bulk selection
<MultiSelectFieldSync
  label="Fruits"
  options={options}
  value={selectedOptions}
  onSelectedOptionsChange={setSelectedOptions}
  selectAll
  selectFiltered
/>

Chip Display Options

Control how selected options are displayed as chips:

Single Row Mode

Restrict the field to a single row height. Overflow chips are collapsed into a “+N” indicator:
<MultiSelectField
  label="Tags"
  loadOptions={loadOptions}
  value={selectedOptions}
  onSelectedOptionsChange={setSelectedOptions}
  singleRow
/>

Max Chips

Limit the number of visible chips regardless of row height:
<MultiSelectField
  label="Tags"
  loadOptions={loadOptions}
  value={selectedOptions}
  onSelectedOptionsChange={setSelectedOptions}
  maxChips={5}
/>

Display Modes

Control how the options menu is displayed using the displayMenuAs prop:
// Automatically choose based on device (default)
<MultiSelectField displayMenuAs="auto" {...props} />

// Always show as popover (not recommended for mobile)
<MultiSelectField displayMenuAs="popover" {...props} />

// Always show as dialog
<MultiSelectField displayMenuAs="dialog" {...props} />

Caching

MultiSelectField caches loadOptions results by default. Configure caching behavior:
// Disable caching
<MultiSelectField cache={{ enabled: false }} {...props} />

// Configure max cache size (default: 50)
<MultiSelectField cache={{ maxSize: 100 }} {...props} />

Clearing the Cache

Use a ref to imperatively clear the cache:
import { useRef } from "react";
import { MultiSelectField } from "@servicetitan/anvil2/beta";

const ExampleComponent = () => {
  const multiSelectRef = useRef(null);

  const handleRefresh = () => {
    multiSelectRef.current?.clearCache();
  };

  return (
    <>
      <MultiSelectField ref={multiSelectRef} {...props} />
      <button onClick={handleRefresh}>Refresh Options</button>
    </>
  );
};

Invalidating Options

Call invalidate() to clear the cache and reload options from the data source. Use this when the underlying data has changed and the component needs to reflect the update:
import { useRef } from "react";
import { MultiSelectField } from "@servicetitan/anvil2/beta";

const ExampleComponent = () => {
  const multiSelectRef = useRef(null);

  const handleDataSourceChange = () => {
    multiSelectRef.current?.invalidate();
  };

  return (
    <MultiSelectField ref={multiSelectRef} {...props} />
  );
};
MultiSelectFieldSync handles this automatically when its options prop changes.

Initial Load Behavior

Control when options are first loaded with the initialLoad prop:
// Load immediately on mount (default)
<MultiSelectField initialLoad="immediate" {...props} />

// Load when user opens the dropdown
<MultiSelectField initialLoad="open" {...props} />

// Auto (currently equivalent to "immediate")
<MultiSelectField initialLoad="auto" {...props} />

Field States

Error State

Display validation errors using the error prop:
<MultiSelectField
  label="Categories"
  loadOptions={loadOptions}
  value={selectedOptions}
  onSelectedOptionsChange={setSelectedOptions}
  error={selectedOptions.length === 0 ? "Please select at least one category" : false}
/>

Hint and Description

Provide additional context with hint and description:
<MultiSelectField
  label="Categories"
  loadOptions={loadOptions}
  value={selectedOptions}
  onSelectedOptionsChange={setSelectedOptions}
  hint="Select up to 5 categories"
  description="These will be used for filtering"
/>

Required Field

Mark a field as required with the required prop:
<MultiSelectField
  label="Categories"
  loadOptions={loadOptions}
  value={selectedOptions}
  onSelectedOptionsChange={setSelectedOptions}
  required
/>

Disabled and ReadOnly

When disabled is set, users cannot interact with the field:
<MultiSelectField
  label="Categories"
  loadOptions={loadOptions}
  value={selectedOptions}
  onSelectedOptionsChange={setSelectedOptions}
  disabled
/>
When readOnly is set, users can see the dropdown but cannot change selections:
<MultiSelectField
  label="Categories"
  loadOptions={loadOptions}
  value={selectedOptions}
  onSelectedOptionsChange={setSelectedOptions}
  readOnly
/>

Prefix and Suffix

Add content before or after the input with prefix and suffix:
<MultiSelectField
  label="Tags"
  loadOptions={loadOptions}
  value={selectedOptions}
  onSelectedOptionsChange={setSelectedOptions}
  prefix="#"
  suffix="tags"
/>

Sizes

Control the size of the field with the size prop:
<MultiSelectField size="small" {...props} />
<MultiSelectField size="medium" {...props} /> {/* default */}
<MultiSelectField size="large" {...props} />

Disabled Options

Individual options can be disabled by setting disabled: true on the option:
const options = [
  { id: 1, label: "Available Option" },
  { id: 2, label: "Unavailable Option", disabled: true },
  { id: 3, label: "Another Available Option" },
];

<MultiSelectField
  label="Select options"
  loadOptions={async () => options}
  value={selectedOptions}
  onSelectedOptionsChange={setSelectedOptions}
/>

Pinned Options

Pin frequently used or suggested options above the list using the pinned prop. Each pinned section requires a label and an options value, which can be a static array or a dynamic loader function.

Static Pinned Options

Pass an object with label and a static options array:
<MultiSelectField
  label="Books"
  pinned={{
    label: "Favorites",
    options: [
      { id: "fav-1", label: "The Martian" },
      { id: "fav-2", label: "Dune" },
    ],
  }}
  loadOptions={fetchBooks}
  value={selectedOptions}
  onSelectedOptionsChange={setSelectedOptions}
/>

Dynamic Pinned Options

Pass a function as options to compute pinned options based on the current search value. This is useful for AI-powered suggestions or context-aware recommendations:
<MultiSelectField
  label="Books"
  pinned={{
    label: "AI Suggestions",
    options: async (searchValue) => {
      const suggestions = await fetchAISuggestions(searchValue);
      return suggestions.map((s) => ({ id: s.id, label: s.title }));
    },
  }}
  loadOptions={fetchBooks}
  value={selectedOptions}
  onSelectedOptionsChange={setSelectedOptions}
/>
By default, the loader re-runs whenever the search value changes. Set searchReactive: false to call the loader once and reuse the result across all search values:
<MultiSelectField
  label="Books"
  pinned={{
    label: "Your Favorites",
    options: async () => {
      return await fetchFavorites();
    },
    searchReactive: false,
  }}
  loadOptions={fetchBooks}
  value={selectedOptions}
  onSelectedOptionsChange={setSelectedOptions}
/>

Multiple Pinned Sections

Pass an array of pinned section objects:
<MultiSelectField
  label="Books"
  pinned={[
    {
      label: "AI Suggestions",
      options: async (searchValue) => {
        const suggestions = await fetchAISuggestions(searchValue);
        return suggestions.map((s) => ({ id: s.id, label: s.title }));
      },
    },
    {
      label: "Your Favorites",
      options: [
        { id: "fav-1", label: "Dune" },
        { id: "fav-2", label: "Foundation" },
      ],
    },
  ]}
  loadOptions={fetchBooks}
  value={selectedOptions}
  onSelectedOptionsChange={setSelectedOptions}
/>

Grouping Options

Options can be organized into visual groups by adding a group property to each option. Groups appear as labeled sections in the dropdown.

Basic Grouping

Add a group property to options and provide a groupToString function to display group labels:
const options = [
  { id: 1, label: "Apple", group: "fruits" },
  { id: 2, label: "Banana", group: "fruits" },
  { id: 3, label: "Carrot", group: "vegetables" },
  { id: 4, label: "Broccoli", group: "vegetables" },
];

<MultiSelectField
  label="Food"
  loadOptions={async () => options}
  groupToString={(group) =>
    group === "fruits" ? "Fruits" : "Vegetables"
  }
  value={selectedOptions}
  onSelectedOptionsChange={setSelectedOptions}
/>

Group Sorting

Use groupSorter to control the order of groups. By default, groups appear in the order they are first encountered in the options array. This prop is available on MultiSelectFieldSync and non-lazy MultiSelectField:
Avoid using groupSorter with lazy="group". When groups load incrementally from the server and get re-sorted, the menu content shifts unexpectedly, creating a disorienting user experience. Instead, have your server return groups in the desired order.
const options = [
  { id: 1, label: "Item A", group: 3 },
  { id: 2, label: "Item B", group: 1 },
  { id: 3, label: "Item C", group: 2 },
];

<MultiSelectField
  label="Items"
  loadOptions={async () => options}
  groupToString={(group) => `Priority ${group}`}
  groupSorter={(a, b) => Number(a) - Number(b)}
  value={selectedOptions}
  onSelectedOptionsChange={setSelectedOptions}
/>

Virtualization

By default, all dropdown options render to the DOM at once. This works well for typical lists but degrades performance with very large option sets as the browser must lay out and paint thousands of elements. Pass virtualize to enable windowed rendering, which only renders the items currently visible in the scroll viewport plus a small overscan buffer.Consider enabling virtualize when the dropdown feels sluggish to open or keyboard navigation becomes laggy. These symptoms typically appear around 200–500 items depending on device performance and item complexity (e.g., items with descriptions are heavier). For smaller lists, the default rendering path is sufficient and avoids the overhead of virtual positioning.Virtualization works with all existing features including lazy loading, pinned options, grouping, select-all/select-filtered bulk actions, and keyboard navigation.
import { useState } from "react";
import { MultiSelectFieldSync } from "@servicetitan/anvil2/beta";

const options = Array.from({ length: 5000 }, (_, i) => ({
  id: i,
  label: `Option ${i + 1}`,
}));

const ExampleComponent = () => {
  const [selectedOptions, setSelectedOptions] = useState([]);

  return (
    <MultiSelectFieldSync
      virtualize
      selectAll
      label="Large dataset"
      placeholder="Search options..."
      options={options}
      value={selectedOptions}
      onSelectedOptionsChange={setSelectedOptions}
    />
  );
};
Pass disableSearch to replace the searchable text input with a non-editable select trigger. The field uses the listbox ARIA pattern instead of combobox, providing a simpler interaction when typing to filter adds no value.This is useful when the option list is short and well-known or you are integrating with an API that does not support search.
import { useState } from "react";
import { MultiSelectFieldSync } from "@servicetitan/anvil2/beta";

const options = [
  { id: 1, label: "Red" },
  { id: 2, label: "Green" },
  { id: 3, label: "Blue" },
  { id: 4, label: "Yellow" },
];

const ExampleComponent = () => {
  const [selectedOptions, setSelectedOptions] = useState([]);

  return (
    <MultiSelectFieldSync
      disableSearch
      selectAll
      label="Colors"
      placeholder="Select colors"
      options={options}
      value={selectedOptions}
      onSelectedOptionsChange={setSelectedOptions}
    />
  );
};
When disableSearch is enabled, selectFiltered has no effect since there is no search input to produce filtered results.
Last modified on March 6, 2026