Skip to content

Latest commit

 

History

History
193 lines (155 loc) · 6.8 KB

useAutocomplete.mdx

File metadata and controls

193 lines (155 loc) · 6.8 KB

{/* Copyright 2025 Adobe. All rights reserved. This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */}

import {Layout} from '@react-spectrum/docs'; export default Layout;

import docs from 'docs:@react-aria/autocomplete'; import {FunctionAPI, HeaderInfo, InterfaceType, TypeContext, TypeLink, PageDescription} from '@react-spectrum/docs'; import i18nDocs from 'docs:@react-aria/i18n'; import packageData from '@react-aria/autocomplete/package.json'; import statelyDocs from 'docs:@react-stately/autocomplete'; import ChevronRight from '@spectrum-icons/workflow/ChevronRight';


category: Pickers keywords: [autocomplete, autosuggest, typeahead, search, aria] preRelease: beta

useAutocomplete

{docs.exports.useAutocomplete.description}

<HeaderInfo packageData={packageData} componentNames={['useAutocomplete']} />

API

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:

<TypeContext.Provider value={docs.links}> <InterfaceType properties={docs.links[docs.exports.useAutocomplete.return.base?.id ?? docs.exports.useAutocomplete.return.id].properties} /> </TypeContext.Provider>

State is managed by the 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 state = useAutocompleteState(props);
  let inputRef = useRef<HTMLInputElement | null>(null);
  let collectionRef = useRef<HTMLElement>(null);
  let {
    textFieldProps,
    collectionProps,
    collectionRef: mergedCollectionRef,
    filter: filterFn
  } = useAutocomplete({
    ...props,
    filter: contains,
    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 ```css hidden @import '../../../react-aria-components/docs/Checkbox.mdx' layer(checkbox); @import '../../../react-aria-components/docs/SearchField.mdx' layer(searchfield); @import '../../../react-aria-components/docs/ListBox.mdx' layer(listbox); ```
@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.