Skip to content

Multiple selection support for useComboBox #2140

Closed

Description

@stephenh

🙋 Feature Request

Update useComboBox to support multiple selection.

🔦 Context

We're building a type-ahead SelectField / MultiSelectField components, both on top of useComboBox and having to support multiple selections is of course making us do some hacky things, b/c it's not really supported.

I.e. we're not passing selectedKey to useComboBox b/c in a multiple selection scenario, the selectedKey could change, and so then odd things happen where useComboBox thinks its not controlled and/or the selectedKey !== inputValue, so it invokes various closing/reset behavior that we didn't mean to trigger.

Obviously this is on us for misusing useComboBox :-D , so just filing a request / wish list for it to get official multiple selection support. Thanks!

Activity

  1. devongovett commented on Jul 24, 2021

    @devongovett
    Member

    We call this a tag field - a combination of a tag list and an input kinda like the "to" field in an email app. It's on the roadmap, but not sure when yet. We need to do some a11y research and testing to determine how best to implement it.

  2. stephenh commented on Jul 27, 2021

    @stephenh
    Author

    @LFDanLu lazy ask, but is there a ticket created for the tag field that @devongovett mentioned? I'd like to follow it, so that I can see when react-aria lands support for it. Thanks!

  3. LFDanLu commented on Jul 27, 2021

    @LFDanLu
    Member

    @stephenh I don't believe there is a ticket created for the tag field yet since it is still in its early germination phase unfortunately. https://github.com/adobe/react-spectrum/projects/1 is the best place to look regarding what is currently in flight.

  4. devongovett commented on Jul 29, 2021

    @devongovett
    Member

    Going to keep this ticket open for tracking.

  5. added
    enhancement
    on Aug 4, 2021
  6. devongovett commented on Aug 19, 2021

    @devongovett
    Member

    More like the second one, the first is only a select not a combobox (no textfield). Think similar to an email entry field like in Gmail. Here's a screenshot of the design from Spectrum that we'd be basing the pattern on:

    tag-field_hero_desktop@2x_6md9yFlaUX9BDThTdZNbgC_1611704216000

  7. ashiskumar-1999 commented on Aug 19, 2021

    @ashiskumar-1999

    @devongovett
    If this falls under priority, I can start working on it.

  8. ashiskumar-1999 commented on Aug 22, 2021

    @ashiskumar-1999

    Hey, @devongovett As I move forward trying to contribute to this task, I'm wondering if this use-case requires us to build another independent component/hook or this functionality could be incorporated into any existing component?

  9. beamery-tomht commented on Sep 8, 2021

    @beamery-tomht
    Contributor

    Is there a way to achieve this behaviour with existing hooks in react-stately and react-aria?

    I'm working on a custom component library according to a design system and using react-aria extensively (without spectrum) and a multi-select is a new requirement. It would be great if we could leverage react-aria for this without having to lean on another library or build something from scratch.

    From what I can see, some combination of a SelectionManager and ListBox looks like the most suitable approach

  10. jamesonhill commented on Jan 5, 2022

    @jamesonhill

    Is there a way to achieve this behaviour with existing hooks in react-stately and react-aria?

    I'm working on a custom component library according to a design system and using react-aria extensively (without spectrum) and a multi-select is a new requirement. It would be great if we could leverage react-aria for this without having to lean on another library or build something from scratch.

    From what I can see, some combination of a SelectionManager and ListBox looks like the most suitable approach

    This also matches my use case. Are we better off building something from scratch or is support for this use case on the near term roadmap?

  11. crazko commented on Jan 14, 2022

    @crazko

    Is there a way to achieve this behaviour with existing hooks in react-stately and react-aria?

    I'm working on a custom component library according to a design system and using react-aria extensively (without spectrum) and a multi-select is a new requirement. It would be great if we could leverage react-aria for this without having to lean on another library or build something from scratch.

    From what I can see, some combination of a SelectionManager and ListBox looks like the most suitable approach

    I was facing this problem regarding multiselect as well. Since @react-aria/select and suitable stately hooks do not support multiple selection mode (and I totally get why it is the case), I followed the implementation of the Picker component, re-created hooks to support our needs (multiple selection, searching possibility, clear & select all buttons...) and built a new Select component with them.

    So, instead of:

    Basically it means a lot of copy-pasting and playing with properties of hooks underneath. Once I became more familiar with the original implementation I found it very flexible and customizable.

  12. 43 remaining items

  13. romansndlr commented on Oct 29, 2024

    @romansndlr
    Contributor

    Hate to ask, but has the TagField been prioritized at all?

    @mryechkin we are waiting on our design team to redesign the component (scheduled likely for later this year) before engineering picks up the component for implementation

    Hi, is there maybe an update on this?

  14. matthewdeutsch commented on Oct 31, 2024

    @matthewdeutsch
    Collaborator

    @romansndlr our design team has picked up the TagField component from their backlog this month and has begun working through specifications, with designs to follow; in the meantime, our implementation is still on hold, but stay tuned 🤞

  15. romansndlr commented on Nov 27, 2024

    @romansndlr
    Contributor

    @romansndlr our design team has picked up the TagField component from their backlog this month and has begun working through specifications, with designs to follow; in the meantime, our implementation is still on hold, but stay tuned 🤞

    That's amazing! Thank you guys so much. Would love it if y'all could keep us updated here on any advancements

  16. lsalling commented on Jan 23, 2025

    @lsalling

    Hey, any updates on this one?

  17. eashish93 commented on Mar 22, 2025

    @eashish93

    This is full implementation of multi-select using claude sonnet 3.7 (thinking). I did it in almost 30+ prompts. But working correctly.

    import {
      Button,
      Label,
      ListBox,
      ListBoxItem,
      Popover,
      FieldError,
      Text,
      Input,
      ComboBox,
      MenuTrigger,
    } from 'react-aria-components';
    import type {
      ListBoxItemProps,
      ValidationResult,
      Key,
      Selection,
      ComboBoxProps as AriaComboBoxProps,
    } from 'react-aria-components';
    import { cx } from 'cva';
    import React, { forwardRef, type ForwardedRef, useState, useRef, useEffect } from 'react';
    
    // Simple down arrow icon
    const IconChevronDown = ({ size = 16 }) => (
      <svg 
        width={size} 
        height={size} 
        viewBox="0 0 16 16" 
        fill="none" 
        xmlns="http://www.w3.org/2000/svg"
      >
        <path d="M4 6L8 10L12 6" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
      </svg>
    );
    
    // Simple X icon for removing tags
    const IconX = ({ size = 12 }) => (
      <svg 
        width={size} 
        height={size} 
        viewBox="0 0 12 12" 
        fill="none" 
        xmlns="http://www.w3.org/2000/svg"
      >
        <path d="M9 3L3 9M3 3L9 9" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
      </svg>
    );
    
    export interface MultiSelectProps<T extends object> {
      label?: string;
      labelClassName?: string;
      children: React.ReactNode;
      helpText?: string | React.ReactNode;
      errorMessage?: string | ((v: ValidationResult) => string);
      items?: Iterable<T>;
      className?: string;
      isDisabled?: boolean;
      isRequired?: boolean;
      isInvalid?: boolean;
      placeholder?: string;
      selectedKeys?: Selection;
      defaultSelectedKeys?: Selection;
      onSelectionChange?: (keys: Selection) => void;
    }
    
    function AriaMultiSelect<T extends object>(
      {
        label,
        labelClassName,
        children,
        items,
        helpText,
        errorMessage,
        className,
        isDisabled,
        isInvalid,
        isRequired,
        placeholder = "Select options",
        selectedKeys: externalSelectedKeys,
        defaultSelectedKeys,
        onSelectionChange: externalOnSelectionChange,
        ...props
      }: MultiSelectProps<T>,
      ref: ForwardedRef<HTMLDivElement>
    ) {
      // Local selection state if not controlled externally
      const [localSelectedKeys, setLocalSelectedKeys] = useState<Selection>(
        defaultSelectedKeys || new Set([])
      );
      
      // For input value in ComboBox
      const [inputValue, setInputValue] = useState('');
      
      // Use controlled or uncontrolled selection
      const selectedKeys = externalSelectedKeys !== undefined ? externalSelectedKeys : localSelectedKeys;
      
      // Handle selection change
      const handleSelectionChange = (key: Key | null) => {
        if (key && typeof selectedKeys !== 'string') {
          // Create a new set with the existing keys
          const newKeys = new Set(selectedKeys);
          
          // Add the key if it doesn't exist, otherwise remove it
          if (newKeys.has(key)) {
            newKeys.delete(key);
          } else {
            newKeys.add(key);
          }
          
          // Update selection
          if (externalOnSelectionChange) {
            externalOnSelectionChange(newKeys);
          } else {
            setLocalSelectedKeys(newKeys);
          }
          
          // Clear input value after selection
          setInputValue('');
        }
      };
      
      // Reference to the input wrapper for positioning the popover
      const inputWrapperRef = useRef<HTMLDivElement>(null);
      
      // Reference to the input element for focus management
      const inputRef = useRef<HTMLInputElement>(null);
      
      // Filter function for ComboBox that filters by input text and excludes selected items
      const filterItems = (textValue: string, inputValue: string) => {
        return textValue.toLowerCase().includes(inputValue.toLowerCase());
      };
      
      // Track the open state of the dropdown
      const [isOpen, setIsOpen] = useState(false);
      
      // Track whether user is in the middle of removing an item
      const [isRemoving, setIsRemoving] = useState(false);
      
      // Convert selection to array for easier handling
      const selectedKeysArray = typeof selectedKeys !== 'string' ? Array.from(selectedKeys || []) : [];
      
      // Remove a selected item
      const removeItem = (key: Key) => {
        if (typeof selectedKeys !== 'string') {
          const newKeys = new Set(selectedKeys);
          newKeys.delete(key);
          
          if (externalOnSelectionChange) {
            externalOnSelectionChange(newKeys);
          } else {
            setLocalSelectedKeys(newKeys);
          }
        }
      };
      
      // This special effect ensures the dropdown stays open when we want it to
      useEffect(() => {
        if (isRemoving && !isOpen) {
          setIsOpen(true);
        }
      }, [isOpen, isRemoving]);
      
      // Get display text for a key
      const getDisplayText = (key: Key): string => {
        // Try to find from ListBoxItem elements
        const allChildren = React.Children.toArray(children);
        
        const result = allChildren.find((child) => {
          if (React.isValidElement(child)) {
            const childProps = child.props as any;
            const childKey = child.key?.toString().replace(/^\$/, '') || childProps.id || childProps.value;
            return String(childKey) === String(key);
          }
          return false;
        });
        
        if (result && React.isValidElement(result)) {
          const props = result.props as any;
          if (props.textValue) return props.textValue;
          if (typeof props.children === 'string') return props.children;
        }
        
        // Try direct text matching for common items
        if (typeof key === 'string') {
          // Match text directly with the key
          const textDirectMatch = allChildren.find(child => {
            if (React.isValidElement(child)) {
              const props = child.props as any;
              if (typeof props.children === 'string' && props.children.toLowerCase() === key.toLowerCase()) {
                return true;
              }
              if (props.textValue && props.textValue.toLowerCase() === key.toLowerCase()) {
                return true;
              }
            }
            return false;
          });
          
          if (textDirectMatch && React.isValidElement(textDirectMatch)) {
            const props = textDirectMatch.props as any;
            return typeof props.children === 'string' ? props.children : props.textValue;
          }
        }
        
        // If not found, return the key itself
        return String(key);
      };
      
      // Handle keyboard events
      const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
        // If Backspace is pressed while input is empty, remove the last selected item
        if (e.key === 'Backspace' && inputValue === '' && typeof selectedKeys !== 'string') {
          const keysArray = Array.from(selectedKeys);
          if (keysArray.length > 0) {
            const lastKey = keysArray[keysArray.length - 1];
            removeItem(lastKey);
            // Prevent default behavior
            e.preventDefault();
            e.stopPropagation();
          }
        }
      };
      
      // For forwarding the ref
      const combinedRef = (node: HTMLDivElement) => {
        if (typeof ref === 'function') {
          ref(node);
        } else if (ref) {
          ref.current = node;
        }
      };
      
      return (
        <div ref={combinedRef} className={className}>
          {label && (
            <Label
              className={cx('block mb-1 font-medium', isInvalid && 'text-red-500', labelClassName)}>
              {label}
              {isRequired && <span className="text-red-500 ml-1">*</span>}
            </Label>
          )}
    
          <ComboBox
            inputValue={inputValue}
            onInputChange={setInputValue}
            onSelectionChange={handleSelectionChange}
            menuTrigger="focus"
            items={items}
            isDisabled={isDisabled}
            aria-label={label}
            selectedKey={null} // Force no single selection
            disabledKeys={selectedKeysArray} // Disable already selected items
            defaultFilter={filterItems} // Apply text filtering
            onOpenChange={setIsOpen}
          >
            <div
              ref={inputWrapperRef}
              className={cx(
                'flex items-center border rounded min-h-[56px]',
                isInvalid ? 'border-red-500' : 'border-gray-300',
                isDisabled && 'opacity-50 cursor-not-allowed'
              )}>
              <div className="flex flex-grow flex-wrap gap-1 items-center pl-3">
                {selectedKeys &&
                  typeof selectedKeys !== 'string' &&
                  Array.from(selectedKeys).length > 0 && (
                    <div className="flex flex-wrap gap-1 my-1 mr-1">
                      {Array.from(selectedKeys).map((key) => (
                        <span
                          key={String(key)}
                          className="bg-gray-100 rounded flex items-center gap-1 px-2 py-1 text-sm">
                          {getDisplayText(key)}
                          <div
                            role="button"
                            tabIndex={0}
                            aria-label={`Remove ${getDisplayText(key)}`}
                            className="hover:bg-gray-200 rounded-full p-0.5 cursor-pointer"
                            onMouseDown={(e) => {
                              // Prevent default to avoid losing focus
                              e.preventDefault();
                              e.stopPropagation();
                            }}
                            onClick={(e) => {
                              removeItem(key);
                              // Prevent default to avoid dropdown closing
                              e.preventDefault();
                              e.stopPropagation();
                              // Focus back on the input field
                              inputRef.current?.focus();
                            }}
                            onKeyDown={(e) => {
                              if (e.key === 'Enter' || e.key === ' ') {
                                removeItem(key);
                                // Prevent default to avoid dropdown closing
                                e.preventDefault();
                                e.stopPropagation();
                                // Focus back on the input field
                                inputRef.current?.focus();
                              }
                            }}>
                            <IconX />
                          </div>
                        </span>
                      ))}
                    </div>
                  )}
                <Input
                  ref={inputRef}
                  className="flex-1 min-w-[50px] outline-none p-2 rounded-sm border-none"
                  placeholder={
                    selectedKeys &&
                    typeof selectedKeys !== 'string' &&
                    Array.from(selectedKeys).length > 0
                      ? ''
                      : placeholder
                  }
                  onKeyDown={handleKeyDown}
                />
              </div>
              <Button className="px-3 appearance-none outline-none bg-transparent">
                <IconChevronDown aria-hidden="true" />
              </Button>
            </div>
    
            <Popover
              containerPadding={0}
              triggerRef={inputWrapperRef}
              className={cx(
                'min-w-[--trigger-width] py-2 overflow-auto rounded-md border border-on-secondary-container/[0.08] shadow-sm bg-white',
                'entering:animate-in entering:fade-in exiting:animate-out exiting:fade-out'
              )}
              // Fix: https://github.com/adobe/react-spectrum/issues/5331 (popover width inside modal is wrong)
              style={{
                width: inputWrapperRef.current
                  ? `${inputWrapperRef.current.getBoundingClientRect().width}px`
                  : undefined,
              }}>
              <ListBox
                items={items}
                selectionMode="multiple"
                selectedKeys={selectedKeys}
                disabledKeys={selectedKeysArray}
                onSelectionChange={(keys) => {
                  // Do nothing - we handle this through ComboBox's onSelectionChange
                  // This prevents double selection handling
                }}
                disallowEmptySelection={false}
                className="p-1 outline-none"
                autoFocus="first">
                {children}
              </ListBox>
            </Popover>
          </ComboBox>
    
          {helpText && !isInvalid && <div className="text-sm text-gray-500 mt-1">{helpText}</div>}
    
          {isInvalid && <FieldError className="text-sm text-red-500 mt-1">{errorMessage}</FieldError>}
        </div>
      );
    }
    
    // ListBoxItem implementation
    function AriaListBoxItem(
      { className, ...props }: ListBoxItemProps,
      ref: ForwardedRef<HTMLDivElement>
    ) {
      return (
        <ListBoxItem
          {...props}
          ref={ref}
          className={cx(
            "px-3 py-2 rounded cursor-pointer outline-none",
            "hover:bg-gray-100",
            "selected:bg-gray-100 selected:font-medium",
            "focus:bg-gray-100",
            "disabled:opacity-50 disabled:cursor-default disabled:hover:bg-transparent disabled:text-gray-400",
            className
          )}
        />
      );
    }
    
    const _AriaListBoxItem = forwardRef(AriaListBoxItem) as <T>(
      props: ListBoxItemProps<T> & { ref?: React.ForwardedRef<HTMLDivElement> }
    ) => React.ReactElement;
    
    const _MultiSelect = forwardRef(AriaMultiSelect) as <T extends object>(
      props: MultiSelectProps<T> & { ref?: React.ForwardedRef<HTMLDivElement> }
    ) => React.ReactElement;
    
    export { _MultiSelect as MultiSelect, _AriaListBoxItem as ListBoxItem };
    
  18. lixiaoyan commented on Sep 24, 2025

    @lixiaoyan
    Contributor
    1. Assistive technology wouldn't know how to announce multiple selection in a combobox.

    Hi @snowystinger, is it possible to create a searchable, accessible multi-select that functions similarly to a multi-select combobox?

  19. muhammadhaffad commented on Sep 29, 2025

    @muhammadhaffad

    This is my custom implementation of a multi-combobox, combined with <select multiple />.

    Feedback and corrections are welcome.

    Reference combobox: https://stackblitz.com/edit/vitejs-vite-iycf5n

    import { useFormValidation } from "@react-aria/form";
    import { useFormValidationState } from "@react-stately/form";
    import { useRef, useState } from "react";
    import { FormContext, Group, TableBody, TagList, useSlottedContext } from "react-aria-components";
    import { useListData } from "react-stately";
    import { ComboBox, ComboBoxItem } from "@/components/ui/ComboBox";
    import { Tag, TagGroup } from "@/components/ui/TagGroup";
    
    function MultiComboBox({ items, selectedItems, isRequired = false, name = '', ...props }) {
        const selectRef = useRef();
        const formContext = useSlottedContext(FormContext) || {};
        const validationState = useFormValidationState({
            isRequired: isRequired,
            name: name,
            validationBehavior: formContext.validationBehavior,
            value: selectedItems
        });
        useFormValidation({
    		validationBehavior: formContext.validationBehavior,
    		focus: () => selectRef.current?.focus()
    	}, validationState, selectRef);
        const list = useListData({
            initialItems: selectedItems,
        });
        const availableList = useListData({
            initialItems: items.filter((item) => !selectedItems.map((item) => item.id).includes(item.id)),
        });
        return (
            <Group>
                <select
                    className="hidden"
                    multiple
                    value={list.items.map((item) => item.id)}
                    onChange={() => { }}
                    required={isRequired}
                    name={name}
                    ref={selectRef}
                >
                    {items.map((item) => (
                        <option key={item.id} value={item.id}>
                            {item.name}
                        </option>
                    ))}
                </select>
                <TagGroup onRemove={(keys) => {
                    let key = keys.values().next().value;
                    availableList.append(list.getItem(key));
                    list.remove(key);
                    validationState.commitValidation();
                }}>
                    <TagList items={list.items}>
                        {(item) => <Tag id={item.id}>{item.name}</Tag>}
                    </TagList>
                </TagGroup>
                <ComboBox
                    items={availableList.items}
                    renderEmptyState={() => <p className="text-center p-2">No available permissions</p>}
                    onSelectionChange={(key) => {
                        if (!availableList.getItem(key)) {
                            return;
                        }
                        list.append(availableList.getItem(key));
                        availableList.remove(key);
                        validationState.commitValidation();
                        console.info(validationState);
                    }}
                    selectedKey={null}
                    allowsEmptyCollection
                    isInvalid={validationState.displayValidation.isInvalid}
                    errorMessage={validationState.displayValidation.validationErrors.join(', ')}
                    {...props}
                >
                    {(item) => <ComboBoxItem id={item.id}>{item.name}</ComboBoxItem>}
                </ComboBox>
            </Group>
        );
    }
    
  20. devongovett commented on Oct 3, 2025

    @devongovett
    Member

    In React Aria Components v1.13.0 released today, we have support for multiple selection in the Select component! See https://react-spectrum.adobe.com/react-aria/Select.html#multiple-selection.

    This can be combined with TagGroup and Autocomplete to create something similar to a multi-select ComboBox: https://stackblitz.com/edit/rac-select-taggroup?file=src%2FExample.tsx

    We do still plan to introduce a TagField component in the future which will be like a TagGroup but with inline editing similar to the "To" field in gmail, but the multiple Select component should cover a good number of use cases as well.

  21. berkerdemirer commented on Oct 17, 2025

    @berkerdemirer

    I have one question regarding the proposed solution. When page is navigated by using tab and VoiceOver, the first focus is on the TagGroup. How does the user will know they are actually inside of a Select? If only they tab and focus to the plus button they can hear that its a Select.

  22. snowystinger commented on Oct 19, 2025

    @snowystinger
    Member

    It announces "Selected states, group" and the next tab announces "Selected States, states, listbox popup collapsed"
    So I think it's not a big leap to associate the two elements. However, you could add an element around the whole thing with role="group" and add information there, or it could be added to just the aria-label for the TagGroup itself.

    What are you expecting to be announced though? Or what would be announced in your ideal world? Maybe we can offer better suggestions knowing that.

  23. berkerdemirer commented on Oct 20, 2025

    @berkerdemirer

    I will try out the group solution. My main concern was that when users are in "selected states, group" they might not know that it is a select field component. So, there is no hint of what next tab might be. IMO, it should be announced that the user is currently inside of a select field, viewing the selected items and that next tab focus will be the select field's trigger. Hard to put into words but that's the idea.

  24. lixiaoyan commented on Dec 8, 2025

    @lixiaoyan
    Contributor

    I still think that we should allow multiple selection in comboboxes. It already exists in a native input.
    https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Attributes/multiple#email_input

  25. berkerdemirer commented on Dec 15, 2025

    @berkerdemirer

    In the end, i ended up using downshiftjs and created my own component

  26. moved this from ✏️ To Groom to ✅ Done in RSP Component Milestoneson Feb 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    ComboBoxenhancement

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions