beta

useAutocomplete

Provides the behavior and accessibility implementation for an autocomplete component. An autocomplete combines a text input with a collection, allowing users to filter the collection's contents match a query.

installyarn add @react-aria/autocomplete
version3.0.0-beta.1
usageimport {useAutocomplete} from '@react-aria/autocomplete'

API#


useAutocomplete( (props: AriaAutocompleteOptions, , state: AutocompleteState )): AutocompleteAria

Features#


Autocomplete can be implemented using the <datalist> HTML element, but this has limited functionality and behaves differently across browsers. useAutocomplete helps achieve accessible text input and collection that can be styled as needed.

useAutocomplete can be used to build UI patterns such as command palettes, searchable menus, and filterable selects.

  • Flexible – Support for multiple input types and collection types, controlled and uncontrolled state, and custom filter functions.
  • Keyboard navigation – an Autocomplete can be navigated using the arrow keys, along with page up/down, home/end, etc. The list of options is filtered while typing into the input, and items can be selected with the enter key.
  • Accessible – Follows the ARIA autocomplete pattern, with support for any collections.

Anatomy#


An autocomplete consists of a text input that displays the current value and a collection of items. Users can type within the input to filter the collection. useAutocomplete handles exposing the correct ARIA attributes for accessibility for each of the elements comprising the autocomplete.

useAutocomplete returns props that you should spread onto the appropriate elements:

NameTypeDescription
textFieldPropsAriaTextFieldPropsProps for the autocomplete textfield/searchfield element. These should be passed to the textfield/searchfield aria hooks respectively.
collectionPropsCollectionOptionsProps for the collection, to be passed to collection's respective aria hook (e.g. useMenu).
collectionRefRefObject<HTMLElementnull>Ref to attach to the wrapped collection.
filter( (nodeTextValue: string )) => booleanA filter function that returns if the provided collection node should be filtered out of the collection.

State is managed by the useAutocompleteState hook from @react-stately/autocomplete. The state object should be passed as an option to useAutocomplete.

Example#


This example uses React Aria Components and shows how, if you need to build your own Autocomplete component, you can integrate it with existing React Aria Components. This Autocomplete uses a SearchField as the input and controls a ListBox. See those docs for examples of what they can do or how to customize them. This Autocomplete renders no dom, so see those components for styling as well.

import {AriaAutocompleteProps, useAutocomplete} from '@react-aria/autocomplete';
import {useAutocompleteState} from '@react-stately/autocomplete';
import {useRef} from 'react';
import {
  Label,
  Text,
  InputContext,
  Input,
  Provider,
  SearchFieldContext,
  SearchField,
  ListBox,
  ListBoxItem,
  useFilter,
  UNSTABLE_InternalAutocompleteContext
} from 'react-aria-components'

interface AutocompleteProps extends AriaAutocompleteProps {}

function Autocomplete(props: AutocompleteProps) {
  let {contains} = useFilter({ sensitivity: 'base' });
  let filter = (textValue, inputValue) => contains(textValue, inputValue);
  let {disableAutoFocusFirst} = props;
  let state = useAutocompleteState(props);
  let inputRef = useRef<HTMLInputElement | null>(null);
  let collectionRef = useRef<HTMLElement>(null);
  let {
    textFieldProps,
    collectionProps,
    collectionRef: mergedCollectionRef,
    filter: filterFn
  } = useAutocomplete({
    ...props,
    filter,
    disableAutoFocusFirst,
    inputRef,
    collectionRef
  }, state);

  return (
    <Provider
      values={[
        [SearchFieldContext, textFieldProps],
        [InputContext, {ref: inputRef}],
        [UNSTABLE_InternalAutocompleteContext, {
          filter: filterFn,
          collectionProps,
          collectionRef: mergedCollectionRef
        }]
      ]}>
      {props.children}
    </Provider>
  );
};

<div className="autocomplete">
  <Autocomplete>
    <SearchField>
      <Label>Favorite animal</Label>
      <Input />
      <Text slot="description">Please select a pet below.</Text>
    </SearchField>
    <ListBox selectionMode="single" aria-label="Possible pets">
      <ListBoxItem id="red panda">Red Panda</ListBoxItem>
      <ListBoxItem id="cat">Cat</ListBoxItem>
      <ListBoxItem id="dog">Dog</ListBoxItem>
      <ListBoxItem id="aardvark">Aardvark</ListBoxItem>
      <ListBoxItem id="kangaroo">Kangaroo</ListBoxItem>
      <ListBoxItem id="snake">Snake</ListBoxItem>
    </ListBox>
  </Autocomplete>
</div>
import {
  AriaAutocompleteProps,
  useAutocomplete
} from '@react-aria/autocomplete';
import {useAutocompleteState} from '@react-stately/autocomplete';
import {useRef} from 'react';
import {
  Input,
  InputContext,
  Label,
  ListBox,
  ListBoxItem,
  Provider,
  SearchField,
  SearchFieldContext,
  Text,
  UNSTABLE_InternalAutocompleteContext,
  useFilter
} from 'react-aria-components';

interface AutocompleteProps extends AriaAutocompleteProps {}

function Autocomplete(props: AutocompleteProps) {
  let { contains } = useFilter({ sensitivity: 'base' });
  let filter = (textValue, inputValue) =>
    contains(textValue, inputValue);
  let { disableAutoFocusFirst } = props;
  let state = useAutocompleteState(props);
  let inputRef = useRef<HTMLInputElement | null>(null);
  let collectionRef = useRef<HTMLElement>(null);
  let {
    textFieldProps,
    collectionProps,
    collectionRef: mergedCollectionRef,
    filter: filterFn
  } = useAutocomplete({
    ...props,
    filter,
    disableAutoFocusFirst,
    inputRef,
    collectionRef
  }, state);

  return (
    <Provider
      values={[
        [SearchFieldContext, textFieldProps],
        [InputContext, { ref: inputRef }],
        [UNSTABLE_InternalAutocompleteContext, {
          filter: filterFn,
          collectionProps,
          collectionRef: mergedCollectionRef
        }]
      ]}
    >
      {props.children}
    </Provider>
  );
}

<div className="autocomplete">
  <Autocomplete>
    <SearchField>
      <Label>Favorite animal</Label>
      <Input />
      <Text slot="description">
        Please select a pet below.
      </Text>
    </SearchField>
    <ListBox
      selectionMode="single"
      aria-label="Possible pets"
    >
      <ListBoxItem id="red panda">Red Panda</ListBoxItem>
      <ListBoxItem id="cat">Cat</ListBoxItem>
      <ListBoxItem id="dog">Dog</ListBoxItem>
      <ListBoxItem id="aardvark">Aardvark</ListBoxItem>
      <ListBoxItem id="kangaroo">Kangaroo</ListBoxItem>
      <ListBoxItem id="snake">Snake</ListBoxItem>
    </ListBox>
  </Autocomplete>
</div>
import {
  AriaAutocompleteProps,
  useAutocomplete
} from '@react-aria/autocomplete';
import {useAutocompleteState} from '@react-stately/autocomplete';
import {useRef} from 'react';
import {
  Input,
  InputContext,
  Label,
  ListBox,
  ListBoxItem,
  Provider,
  SearchField,
  SearchFieldContext,
  Text,
  UNSTABLE_InternalAutocompleteContext,
  useFilter
} from 'react-aria-components';

interface AutocompleteProps
  extends
    AriaAutocompleteProps {}

function Autocomplete(
  props:
    AutocompleteProps
) {
  let { contains } =
    useFilter({
      sensitivity: 'base'
    });
  let filter = (
    textValue,
    inputValue
  ) =>
    contains(
      textValue,
      inputValue
    );
  let {
    disableAutoFocusFirst
  } = props;
  let state =
    useAutocompleteState(
      props
    );
  let inputRef = useRef<
    | HTMLInputElement
    | null
  >(null);
  let collectionRef =
    useRef<HTMLElement>(
      null
    );
  let {
    textFieldProps,
    collectionProps,
    collectionRef:
      mergedCollectionRef,
    filter: filterFn
  } = useAutocomplete({
    ...props,
    filter,
    disableAutoFocusFirst,
    inputRef,
    collectionRef
  }, state);

  return (
    <Provider
      values={[
        [
          SearchFieldContext,
          textFieldProps
        ],
        [InputContext, {
          ref: inputRef
        }],
        [
          UNSTABLE_InternalAutocompleteContext,
          {
            filter:
              filterFn,
            collectionProps,
            collectionRef:
              mergedCollectionRef
          }
        ]
      ]}
    >
      {props.children}
    </Provider>
  );
}

<div className="autocomplete">
  <Autocomplete>
    <SearchField>
      <Label>
        Favorite animal
      </Label>
      <Input />
      <Text slot="description">
        Please select a
        pet below.
      </Text>
    </SearchField>
    <ListBox
      selectionMode="single"
      aria-label="Possible pets"
    >
      <ListBoxItem id="red panda">
        Red Panda
      </ListBoxItem>
      <ListBoxItem id="cat">
        Cat
      </ListBoxItem>
      <ListBoxItem id="dog">
        Dog
      </ListBoxItem>
      <ListBoxItem id="aardvark">
        Aardvark
      </ListBoxItem>
      <ListBoxItem id="kangaroo">
        Kangaroo
      </ListBoxItem>
      <ListBoxItem id="snake">
        Snake
      </ListBoxItem>
    </ListBox>
  </Autocomplete>
</div>
Show CSS
@import "@react-aria/example-theme";

.autocomplete {
  display: flex;
  flex-direction: column;
  gap: 12px;
  max-width: 300px;
  height: 180px;
  border: 1px solid var(--border-color);
  padding: 16px;
  border-radius: 10px;
  background: var(--overlay-background);

  .react-aria-SearchField {
    width: 100%;
  }

  .react-aria-ListBox {
    flex: 1;
    overflow: auto;
  }

  .react-aria-Label {
    margin-bottom: .5em;
  }
}
@import "@react-aria/example-theme";

.autocomplete {
  display: flex;
  flex-direction: column;
  gap: 12px;
  max-width: 300px;
  height: 180px;
  border: 1px solid var(--border-color);
  padding: 16px;
  border-radius: 10px;
  background: var(--overlay-background);

  .react-aria-SearchField {
    width: 100%;
  }

  .react-aria-ListBox {
    flex: 1;
    overflow: auto;
  }

  .react-aria-Label {
    margin-bottom: .5em;
  }
}
@import "@react-aria/example-theme";

.autocomplete {
  display: flex;
  flex-direction: column;
  gap: 12px;
  max-width: 300px;
  height: 180px;
  border: 1px solid var(--border-color);
  padding: 16px;
  border-radius: 10px;
  background: var(--overlay-background);

  .react-aria-SearchField {
    width: 100%;
  }

  .react-aria-ListBox {
    flex: 1;
    overflow: auto;
  }

  .react-aria-Label {
    margin-bottom: .5em;
  }
}

Styled examples#


See Autocomplete examples for a sense of the things that you can build with the useAutocomplete hook.

Internationalization#


useAutocomplete handles some aspects of internationalization automatically. For example, VoiceOver announcements about the item focus, count, and selection are localized. You are responsible for localizing all labels and option content that is passed into the autocomplete.