Skip to content

TagPicker

TagPicker

A multi-select combobox that shows the selected values as removable tags.

- **Two forms.** The array form, <TagPicker options={โ€ฆ} />, is the parts with their defaults: TagPicker.Control (holding TagPicker.Group and TagPicker.Input) and TagPicker.List. The parts form replaces only the part you need: your own Tags in TagPicker.Group (an Avatar in each), rich TagPicker.Options in TagPicker.List, or TagPicker.Button, a select-only trigger, in place of the Input. Render TagPicker.Control and TagPicker.List directly inside TagPicker (a Fragment is fine); without a List the default list is added. options names the values in both forms (media and secondaryContent show in the default options, media in the default tags too); with a List that has children, its options are the options, and the options of selected values stay rendered (TagPicker hides them).
- **Keyboard.** Typing filters the options (filter, by default a case-insensitive match on textValue ?? label); the option whose label equals the typed text becomes active, else the first match. ArrowDown/ArrowUp move the highlight (aria-activedescendant), Enter adds the active option and keeps the list open (with nothing active, Enter is left to the surrounding form), Escape closes the list (and then clears the typed text). Backspace in the empty input, and Left (Right in RTL) with the caret at its start, focus the last tag; Delete, Backspace, Enter or Space on a remove button remove its tag and focus the next tag, else the input; a click on one focuses the input. Additions and removals are announced ("Cherry removed, 2 selected"), and so is "No matches" for text that matches no option.
- **Free tagging.** With allowCreate, text that matches no option label, no selected value (ignoring case) and no option value ends the list with a create option (Create "infra"); Enter on it or a click adds the text as a tag after onOptionCreate(text) and clears the text.
- **End buttons.** A chevron (expandIcon, false hides it) opens and closes the list without taking focus; clearable adds a clear button, a Tab stop after the input, which removes every tag. A press on the field's empty area toggles the list.
- **One line.** overflow="count" keeps the tags on one line while focus is outside the picker and its list is closed; the tags that do not fit give way to "+N".
- **Names.** The tags form a list named "Selected"; the trigger is described by a summary of the selected labels ("Selected: Apple, Banana"). These built-in texts are English; labels localizes them.
- **Routing.** The trigger that renders (TagPicker.Input or TagPicker.Button) receives ref, id, aria-label, aria-labelledby, aria-describedby, aria-invalid, aria-required, aria-errormessage, aria-details, tabIndex and autoFocus; the Input also onFocus/onBlur/onKeyDown/onKeyUp and the text input attributes autoComplete, autoCapitalize, autoCorrect, maxLength, inputMode, spellCheck and enterKeyHint (with the Button, pass handlers on it). ref follows the trigger: the built-in Input, your TagPicker.Input, or TagPicker.Button in its place. className, style, other aria-* attributes and the remaining props stay on the root <div> (slotProps.root.ref reaches it). Inside a Field the trigger is labelled and described by it; the field shows the error look whenever the trigger ends up aria-invalid. With name/required the values take part in form submission, validation and reset. Selected values without a matching option show their raw value.
- **Size and appearance**: size resolves from its own prop, then the surrounding Field's size, then WaveProvider inputDefaults.size, else 'medium' (a Field or provider small gives 'medium' too, since TagPicker has no small); appearance from its own prop, then WaveProvider inputDefaults.appearance, else 'outline'; both render as data-size and data-appearance on the root <div>, and the parts take neither. The tags are one Tag size smaller. The option list keeps its size.
- **Server rendering.** The open list renders only in the browser: an open list (defaultOpen, open) is closed in the server HTML and opens once the picker has hydrated; the tags of registered options show their labels in the server HTML.

Fluent's selectedOptions and onOptionSelect are value and onValueChange (plus onOptionCreate). TagPickerOption is both the type of an options entry and the flat name of TagPicker.Option.

Examples

Default

export const Default: Story = {
  args: {
    placeholder: 'Select fruits...',
  },
};

With Preselected

AppleCherry
export const WithPreselected: Story = {
  args: {
    defaultValue: ['apple', 'cherry'],
    placeholder: 'Select fruits...',
  },
};

Disabled

Banana
export const Disabled: Story = {
  args: {
    defaultValue: ['banana'],
    disabled: true,
  },
};

Read Only

AppleCherry
export const ReadOnly: Story = {
  args: {
    defaultValue: ['apple', 'cherry'],
    readOnly: true,
  },
};

Custom Filter

export const CustomFilter: Story = {
  args: {
    'aria-label': 'Desserts',
    options: [
      { value: 'creme-brulee', label: 'Crรจme brรปlรฉe' },
      { value: 'eclair', label: 'ร‰clair' },
      { value: 'mille-feuille', label: 'Mille-feuille' },
      { value: 'pain-au-chocolat', label: 'Pain au chocolat' },
      { value: 'tarte-tatin', label: 'Tarte Tatin' },
    ],
    placeholder: 'Type the start of a dessert...',
  },
  render: (args) => (
    <TagPicker
      {...args}
      filter={(option: ListboxItem, query: string) => fold(option.label).startsWith(fold(query))}
    />
  ),
};
8 results
export const AsyncSearch: Story = {
  args: {
    'aria-label': 'Countries',
    placeholder: 'Search countries...',
    onQueryChange: fn(),
  },
  render: (args) => <AsyncSearchTagPicker {...args} />,
};

Invalid

export const Invalid: Story = {
  args: {
    'aria-label': undefined,
    placeholder: 'Select fruits...',
  },
  render: (args) => (
    <Field label="Fruits" error="Pick at least one fruit." required>
      <TagPicker {...args} />
    </Field>
  ),
};

Sizes And Appearances

Apple
Apple
Apple
Apple
Apple
Apple
Apple
Apple
Apple
Apple
Apple
Apple
export const SizesAndAppearances: Story = {
  render: (args) => (
    <div className="grid gap-4">
      {(['outline', 'underline', 'filled-darker', 'filled-lighter'] as const).map((appearance) => (
        <div
          key={appearance}
          className={
            appearance === 'filled-lighter'
              ? 'grid grid-cols-3 items-start gap-3 rounded bg-wave-secondary p-3'
              : 'grid grid-cols-3 items-start gap-3 p-3'
          }
        >
          {(['medium', 'large', 'extra-large'] as const).map((size) => (
            <TagPicker
              {...args}
              key={size}
              size={size}
              appearance={appearance}
              options={FRUIT}
              defaultValue={['apple']}
              clearable
              aria-label={`${size} ${appearance}`}
            >
              <TagPicker.Control>
                <TagPicker.Group />
                <TagPicker.Input />
              </TagPicker.Control>
              <TagPicker.List />
            </TagPicker>
          ))}
        </div>
      ))}
    </div>
  ),
};

People Picker

Katri Athokas
export const PeoplePicker: Story = {
  args: { 'aria-label': 'People', placeholder: 'Add people...' },
  render: (args) => <PeoplePickerExample {...args} />,
};

Composed Parts

Banana
export const ComposedParts: Story = {
  render: (args) => <ComposedPartsExample {...args} />,
};

Option Groups

Apple
export const OptionGroups: Story = {
  args: { 'aria-label': 'Produce', defaultValue: ['apple'] },
  render: (args) => (
    <TagPicker {...args} options={undefined}>
      <TagPicker.Control />
      <TagPicker.List>
        <TagPicker.OptionGroup label="Fruit">
          <TagPicker.Option value="apple">Apple</TagPicker.Option>
          <TagPicker.Option value="pear">Pear</TagPicker.Option>
        </TagPicker.OptionGroup>
        <TagPicker.OptionGroup label="Vegetables">
          <TagPicker.Option value="carrot">Carrot</TagPicker.Option>
          <TagPicker.Option value="leek">Leek</TagPicker.Option>
        </TagPicker.OptionGroup>
      </TagPicker.List>
    </TagPicker>
  ),
};

Button Trigger

export const ButtonTrigger: Story = {
  args: { 'aria-label': 'Fruits', placeholder: 'Choose fruits' },
  render: (args) => (
    <TagPicker {...args}>
      <TagPicker.Control>
        <TagPicker.Group />
        <TagPicker.Button />
      </TagPicker.Control>
      <TagPicker.List />
    </TagPicker>
  ),
};

Free Tagging

export const FreeTagging: Story = {
  args: { 'aria-label': 'Topics', placeholder: 'Add topics...', onOptionCreate: fn() },
  render: (args) => <FreeTaggingExample {...args} />,
};
export const FreeTaggingWithAsyncSearch: Story = {
  args: {
    'aria-label': 'Destinations',
    placeholder: 'Search or add...',
    onQueryChange: fn(),
    onOptionCreate: fn(),
  },
  render: (args) => <FreeTaggingAsyncExample {...args} />,
};

Clearable

AppleCherryFig
export const Clearable: Story = {
  args: { clearable: true, defaultValue: ['apple', 'cherry', 'fig'] },
};

Single Line

AppleBananaCherryDateElderberryFig
export const SingleLine: Story = {
  args: {
    overflow: 'count',
    defaultValue: ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig'],
  },
  render: (args) => (
    <div className="w-72">
      <TagPicker {...args} />
    </div>
  ),
};

Expand Icon

export const ExpandIcon: Story = {
  render: (args) => (
    <div className="grid gap-3">
      <TagPicker {...args} aria-label="Fruits with a custom glyph" expandIcon={<span>โ–พ</span>} />
      <TagPicker {...args} aria-label="Fruits without an expand button" expandIcon={false} />
    </div>
  ),
};

Localized Labels

AppleBananaCherryDate
export const LocalizedLabels: Story = {
  args: {
    'aria-label': 'Frukt',
    placeholder: 'Velg frukt...',
    defaultValue: ['apple', 'banana', 'cherry', 'date'],
    clearable: true,
    allowCreate: true,
    overflow: 'count',
    labels: {
      remove: (label) => `Fjern ${label}`,
      selected: 'Valgt',
      summary: (labels) => `Valgt: ${labels.join(', ')}`,
      added: (label, count) => `${label} lagt til, ${count} valgt`,
      removed: (label, count) => `${label} fjernet, ${count} valgt`,
      noMatches: 'Ingen treff',
      create: (text) => `Opprett ยซ${text}ยป`,
      clear: 'Fjern alle',
      expand: 'Vis alternativer',
      overflowCount: (count) => `+${count}`,
    },
  },
  render: (args) => (
    <div className="w-72">
      <TagPicker {...args} />
    </div>
  ),
};

Motion

export const Motion: Story = {
  render: function MotionPopups(args) {
    return (
      <div className="flex flex-wrap gap-4">
        {motionCases(fadeAndZoom).map(({ label, motion }) => (
          <TagPicker
            key={label}
            {...args}
            aria-label={label}
            motion={motion}
            options={fruitOptions}
            placeholder={label}
          />
        ))}
      </div>
    );
  },
};

No Popover

export const NoPopover: Story = {
  args: {
    'aria-label': 'Topics',
    placeholder: 'Type a topic and press Enter',
    noPopover: true,
    allowCreate: true,
    onOptionCreate: fn(),
  },
};

Secondary Action

Apple
export const SecondaryAction: Story = {
  render: (args) => <SecondaryActionExample {...args} />,
};

Disabled Options

export const DisabledOptions: Story = {
  args: {
    options: fruitOptions.map((option) => ({ ...option, disabled: option.value === 'cherry' })),
  },
};

Windowed

export const Windowed: Story = {
  render: (args) => <WindowedExample {...args} />,
};

Props

NameTypeRequiredDefaultDescription
optionsreadonly TagPickerOption[]No

The options, the array form ({ value, label, media?, secondaryContent? }). With parts whose TagPicker.List has children it only names values (tags, announcements). Changed in 0.11: optional.

childrenReact.ReactNodeNo

The parts: TagPicker.Control and TagPicker.List, directly inside TagPicker (a Fragment is fine). Without children TagPicker renders both with their defaults; without a TagPicker.List it renders the default list after the children.

valuereadonly string[]No

Controlled array of selected option values ([] for none). Fluent's selectedOptions.

defaultValuereadonly string[]No[]

Initial selected values for uncontrolled usage; a form reset restores them.

onValueChange(value: string[]) => voidNo

Called with the new selection when it changes: a tag is added (an option, or a created tag) or removed, or a form reset restores different tags. Fluent's onOptionSelect.

openbooleanNo

Controlled open state of the option list. The list renders only in the browser: an open picker is closed in the server HTML and opens once it has hydrated.

defaultOpenbooleanNofalse

Initial open state for uncontrolled usage. A picker that starts disabled or read-only starts closed. The list renders only in the browser: it is closed in the server HTML and opens once the picker has hydrated.

onOpenChange(open: boolean) => voidNo

Called when the option list opens or closes.

placeholderstringNo'Select...'

Shown by TagPicker.Input or TagPicker.Button while no tag is selected; the part's own placeholder wins.

filter(option: ListboxItem, query: string) => booleanNoa case-insensitive substring match on the option's `textValue ?? label`

Whether an option matches the typed text (the query). Called with every listed option, also the options of TagPicker.List's children (its value, label and textValue), and the text whenever the text is not empty, never with a selected option or the create option; an option it returns false for is filtered out. It may keep options that do not contain the text: filter={() => true} with query and onQueryChange leaves the matching to you (a server-side search that replaces options); for a create entry, use allowCreate. With a server-side search, keep the selected options in options (they are never listed): a selected value without an option shows its raw value as the tag label, with a development warning (the "Async search" story does this).

querystringNo

Controlled query: the text typed since the last tag was added, which filters the options and shows in the input (hidden while disabled or readOnly). Not used with TagPicker.Button.

defaultQuerystringNo''

Initial query for uncontrolled usage. A TagPicker that starts disabled or read-only starts without it (as it starts closed). Not used with TagPicker.Button.

onQueryChange(query: string) => voidNo

Called with the new query when it changes: as the user types, and with '' when it resets (a tag added or created, Escape on the closed list, the clear button, a form reset, or disabled or readOnly turned on while text is typed). A blur or a close keeps the text. A TagPicker that mounts disabled or read-only reports nothing: it keeps a controlled query, which shows once it unlocks. Not used with TagPicker.Button.

virtualWindowVirtualWindowNo

Renders only the options in view of a long list of options, plus an overscan, and spacers (aria-hidden, data-virtual-spacer) as tall as the options they stand for: pass the result of useVirtualWindow({ itemSize }), or an object of your own that implements VirtualWindow. It applies to the array form (options, and the create option, which is the last item): with a TagPicker.List that has children, the window is ignored with a development warning, since the options are yours. The open list is the window's scroller (it scrolls within its own maximum height, 15rem), has no block padding while windowed and no scroll anchoring of the browser; every option is exactly itemSize tall (an option with media and secondaryContent needs more than the 32 pixels of one line). The window counts the listed options: typing narrows it, as it narrows aria-setsize. The keys move over all of them, the active option stays rendered while it is scrolled away, and opening the list scrolls the active option to the middle. A closed list renders no option. The server renders no list.

disabledbooleanNofalse

Whether the tag picker is disabled: nothing can be added or removed, the remove buttons leave the tab order, and the expand and clear buttons are disabled. The field dims once.

size'medium' | 'large' | 'extra-large'No

Size of the tags and the field: medium (the 0.7 look), large or extra-large (Fluent's union; TagPicker has no small). Default: the surrounding Field's size, else WaveProvider inputDefaults.size, else 'medium'; a Field or provider small gives 'medium' too. Its tags are one Tag size smaller: medium โ†’ extra-small, large โ†’ small, extra-large โ†’ medium. The option list keeps its size.

positioningPopupPositioningOptionsNo`{ matchReferenceWidth: true, fitViewport: true }`

Advanced positioning of the popup (Fluent's positioning): offset, fitViewport, matchReferenceWidth and fallbackPlacements (tried in order when the requested side has no room). The popup opens below the field.

motionMotionSlot | nullNothe fade and slide above

The popup surface's motion. By default it fades in and slides 4px away from the field, on the side it opened on, over 200 ms with a decelerating curve, and fades out and slides back over 100 ms with an accelerating curve (the list stays in the surface while it exits); under reduced motion it appears and disappears at once. The list does not fade out when its options changed as it closed (a filter reset by the selection), nor does the "No matches" row. null turns the motion off (the surface still renders its data-presence phases, which then end at once); a class string or { className } replaces the default classes with yours (see MotionSlot), also under a WaveProvider with motion="none", which otherwise turns the default off. Fluent's popup surfaceMotion.

appearance'outline' | 'underline' | 'filled-darker' | 'filled-lighter'No

Look of the field: outline (a full border), underline (a bottom stroke only), filled-darker or filled-lighter (a fill without a visible stroke: give the field a visible label). Default: WaveProvider inputDefaults.appearance, else 'outline'. The tags are filled, outlined on filled-darker.

namestringNo

Name of the values in form submissions (one hidden input per value).

formstringNo

Id of the form the values belong to, when the TagPicker is outside it.

requiredbooleanNo

At least one tag is required to submit the form (native constraint validation). Like a native readonly input, a readOnly TagPicker does not block submission.

autoCompletestringNo'off'

The autocomplete attribute of TagPicker.Input's <input role="combobox">. Browser autofill is off unless you set it (for example 'on'). With TagPicker.Button, not used.

maxLengthnumberNo

The maximum length of the typed text (maxlength of TagPicker.Input's <input>). With TagPicker.Button, not used.

readOnlybooleanNo

The selection cannot be changed: the trigger is read-only, the tags have no remove buttons, the expand button is disabled and the clear button hidden, and the option list neither opens (click, keyboard, a controlled open) nor adds tags; Escape is left to the page. Turning it (or disabled) on while the list is open closes it (onOpenChange(false)); a focused remove button hands focus to the trigger.

allowCreatebooleanNofalse

Lets the user add a tag of their own text: while the trimmed text matches no option label and no selected value (ignoring case) and no option value, the list ends with a create option (labels.create); Enter on it or a click adds the text as a tag, calls onOptionCreate, and clears the text. Needs TagPicker.Input (not TagPicker.Button). WaveUI-only: Fluent's TagPicker has no free tagging.

onOptionCreate(text: string, details?: TagPickerCreateDetails) => voidNo

Called with the trimmed text when the user creates a tag, before onValueChange reports the new value, and details.event, the key or click event behind it. Add an option for it if you keep options: until then the tag shows the raw text. WaveUI-only (see allowCreate).

noPopoverbooleanNofalse

Leaves the list out: the picker is a text field that adds tags of its own. There is no popup, no aria-expanded, aria-controls or aria-haspopup, the expand button is not rendered and the input is a plain text field (no role="combobox"). Enter adds the typed text as a tag: the unselected option whose label equals it (ignoring case), else, with allowCreate, a new tag after onOptionCreate; with neither, Enter is left to the page. A TagPicker.List is not rendered, and the TagPicker.Button trigger ignores it (a development warning). Fluent's noPopover only drops the list and leaves the adding to the app's own onKeyDown.

secondaryActionSlot<'span'>No

An action after the trigger, before the end buttons (a clear-all or an "Add all" button): rendered in a <span> (stable class wave-tag-picker__secondary-action) at the end of the field. TagPicker.Control's secondaryAction wins when it is not undefined. Fluent's secondaryAction of TagPickerControl.

clearablebooleanNofalse

Shows a clear button at the end of the field while a tag is selected (not while readOnly; disabled while disabled): it removes every tag (onValueChange([])), clears the typed text, closes the list and focuses the trigger (the input, or TagPicker.Button). A Tab stop after the trigger. The name of Fluent's Combobox and Dropdown prop.

expandIconSlot<'span'>No

The glyph of the expand button at the end of the field (default: a chevron). The button opens and closes the list, keeps focus on the trigger and is not a Tab stop. null or undefined keep the chevron; false, or a value that renders nothing, hides the button. Decorative: a <button> passed here is unwrapped. TagPicker.Control's expandIcon wins.

overflow'wrap' | 'count'No'wrap'

'wrap': the tags wrap onto more lines. 'count': while focus is outside the picker and its list is closed, the tags stay on one line and the ones that do not fit give way to "+N" (labels.overflowCount); focusing the picker shows them all. The tags are measured by position: your own Tags in TagPicker.Group render in value order. WaveUI-only: Fluent's single-line layout is a story, not a prop.

labelsTagPickerLabelsNo

Names of the remove buttons and the tag list, the summary that describes the trigger, the announcements, the "No matches" text, the create option, the clear and expand buttons and the "+N" count, for localization. Unset members keep their English defaults.

onFocusReact.FocusEventHandler<HTMLInputElement>No

Called when TagPicker.Input's <input role="combobox"> receives focus (the root keeps other handlers). With TagPicker.Button, pass it on the Button.

onBlurReact.FocusEventHandler<HTMLInputElement>No

Called when TagPicker.Input's <input> loses focus. With TagPicker.Button, pass it on the Button.

onKeyDownReact.KeyboardEventHandler<HTMLInputElement>No

Called on a key press in TagPicker.Input's <input>, after the Input's own onKeyDown and before the built-in listbox and tag keys; event.preventDefault() skips them. With TagPicker.Button, pass it on the Button.

onKeyUpReact.KeyboardEventHandler<HTMLInputElement>No

Called when a key is released in TagPicker.Input's <input>. With TagPicker.Button, pass it on the Button.

refReact.Ref<HTMLInputElement | HTMLButtonElement>No

Ref to the trigger that renders, the focusable control (Fluent UI's ref, on its primary element): TagPicker.Input's <input role="combobox">, also the one TagPicker renders without children, or TagPicker.Button's <button role="combobox">. It follows the trigger: a parts form that swaps the Input for the Button moves it to the button (a state setter you pass takes state typed for both, or HTMLElement). The part's own ref joins it. The root <div> is slotProps.root.ref.

slotProps{ root?: SlotPart<'div'>; tag?: SlotPart<'span'>; removeButton?: SlotPart<'button'>; expandButton?: SlotPart<'button'>; clearButton?: SlotPart<'button'>; option?: SlotPart<'li'>; createOption?: SlotPart<'li'>; overflowCount?: SlotPart<'span'>; surface?: SlotPart<'div'>; emptyMessage?: SlotPart<'div'> }No

Props for the elements TagPicker generates in its parts, by part, merged into each part's own (Fluent UI's TagPicker parts take their own props, as TagPicker.Control, TagPicker.Group, TagPicker.Input, TagPicker.Button and TagPicker.List do here, and the root <div> is root): your classes after the part's (yours win a conflict), your styles over its styles, your handlers before its handlers (preventDefault() in yours skips TagPicker's handling of the event), your ref beside its ref, and your ids added to its aria-labelledby and aria-describedby. Every attribute TagPicker sets on a part is locked; you add the attributes it does not set. A part takes no children. Besides the root, the parts reach only what TagPicker draws itself: the tags of a TagPicker.Group without children, the end buttons of TagPicker.Control, the "+N" chip, the options of a TagPicker.List without children and the create option; a Tag or an option you write takes its own props. TagPicker puts slotProps in the context its parts read, so keep the object's identity across renders (a constant, or useMemo): a new object each render re-renders every part that reads it.

Any other prop is passed to the element it renders (HTMLDivElement).

Parts

  • root
  • tag
  • removeButton
  • expandButton
  • clearButton
  • option
  • createOption
  • overflowCount
  • surface
  • emptyMessage
  • TagPicker.Control
  • TagPicker.Group
  • TagPicker.Input
  • TagPicker.Button
  • TagPicker.List
  • TagPicker.Option
  • TagPicker.OptionGroup

Stable class names

PartClass
rootwave-tag-picker
tagwave-tag-picker__tag
removeButtonwave-tag-picker__remove-button
inputwave-tag-picker__input
expandButtonwave-tag-picker__expand-button
expandIconwave-tag-picker__expand-icon
clearButtonwave-tag-picker__clear-button
listboxwave-tag-picker__listbox
optionwave-tag-picker__option
createOptionwave-tag-picker__create-option
overflowCountwave-tag-picker__overflow-count
surfacewave-tag-picker__surface
emptyMessagewave-tag-picker__empty-message
spacerwave-tag-picker__spacer
secondaryActionwave-tag-picker__secondary-action