Autocomplete
Baseβ
Autocomplete is a component for selecting values from a list of options that can be filtered based on a typed term.
Presentation modesβ
Autocomplete is displayed as a select (default) or as an input, switching between these two modes can be done via the kind property.
Optionsβ
The options list for an Autocomplete can be generated in two ways:
- Via the
optionsproperty, through an array of objects - Via the
Autocomplete.Optionsubcomponent
Via the options propertyβ
Use the options property to define the list of options for an Autocomplete component. The options property must contain an array of objects and, in general, each of these objects must have the label and value attributes, representing respectively the text and value of the option in the list.
Using an array of options without the label and value attributesβ
Use the getOptionLabel and getOptionValue properties when the array objects do not have a label or value attribute.
Via the Autocomplete.Option subcomponentβ
It is also possible to define the list of options by passing a series of Autocomplete.Option subcomponents as children of the Autocomplete component.
The Autocomplete.Option subcomponent has a number of properties that allow you to customize visual elements such as helper text and icon (see the API documentation for more details). However, these visual elements are not available for the options generated through the options property, as it only allows customization of the text (label).
Autocompleteconsiders only thelabelproperty ofAutocomplete.Optionto filter the listing options- The
getOptionLabelandgetOptionValueproperties have no effect when options are constructed via theAutocomplete.Optionsubcomponent
Multiple selectionβ
By default the user can select only one option among those available in the Autocomplete list, however, through the multiple property it is possible to enable the choice of multiple options.
With the Autocomplete.Option subcomponentβ
The multiple property of Autocomplete also has the same effect for a listing of options generated via the Autocomplete.Option subcomponent.
Disabling optionsβ
Add the disabled property to the Autocomplete.Option subcomponent to disable a specific option.
- Unable to navigate or select disabled options
- You can only disable options through the
Autocomplete.Optionsubcomponent, the same cannot be done through theoptionsproperty ofAutocomplete
Showing a message when there are no optionsβ
Use the renderNoOption property to add a message when there are no options to display.
Initial value and state controlβ
Use the defaultValue property to provide an initial value for the uncontrolled Autocomplete, or use the value property to manage the value of the controlled Autocomplete.
The selected option (or selected options, in the case of an Autocomplete with multiple selection) will be defined through strict equality between the label and value attributes of the options and the value passed to the defaultValue or value property.
Both the defaultValue and value properties are subject to the effects of the getOptionLabel and getOptionvalue properties.
Not controlledβ
You can use the defaultValue parameter to set the initial value of Autocomplete.
Controlledβ
You must create a state to manage the value through the value property when using Autocomplete controlled.
Asynchronous requestsβ
You can asynchronously load Autocomplete options in two different ways:
- When opening
Autocomplete - Based on the text entered while filtering
In both modes it is important to visually show that the component is loading options via the loading property.
Loading options when opening Autocompleteβ
Use the onOpen event to fetch the data needed to dynamically assemble the list of options.
For performance and usability reasons, it is not ideal to fetch the data to build the list of options every time the user opens Autocomplete. Think of caching and retries policies appropriate for your scenario.
Loading options when filteringβ
Use the onInputChange event to fetch the data needed to dynamically assemble the list of options as the user types into the Autocomplete filter.
For performance and usability reasons, it's not ideal to fetch the data to build the options list every time a new character is typed in the Autocomplete filter. Think of optimization strategies like throttle and debounce that are right for your scenario.
Separatorsβ
Use the Autocomplete.Title and Autocomplete.Divider subcomponents to group or separate options.
The use of separators is not available for generating options through the options property of Autocomplete.
Grouper with textβ
Use the Autocomplete.Title subcomponent to group options.
The Autocomplete filter does not take into account the text of the Autocomplete.Title subcomponent.
Divider lineβ
Use the Autocomplete.Divider subcomponent to separate options.
Including footerβ
Use the renderFooter property to render a footer after the options list. This property accepts a component with the following properties:
inputValue: The current value of the inputhasOption: Indicates if any options are displayedclose: Function to closeAutocompleteselectedOption: Selected option, present whenAutocompleteis single selectionselectedOptions: List with selected options, present whenAutocompleteis multiple selectionclearInputValue: Function to clear the value of input
Disabledβ
Use the disabled property of Autocomplete to disable the component as a whole.
With Tag componentβ
With helper textβ
Defaultβ
Use the Form.Feedback subcomponent to include Autocomplete helper texts.
Use the aria-describedby attribute to link the Autocomplete component to the helper text.
Successβ
The success message, as well as its style, should only be applied when the field needs some validation. Success and error states are not directly related to each other.
Errorβ
If Autocomplete is filled in incorrectly, or its criteria are not met, an error message should be displayed as a validation.
After correcting the error, the field state should revert to the default style.
Integration with Form.Controlβ
As with other form components, the Autocomplete component is integrated with the Form.Control subcomponent and receives the error and success properties automatically through this integration.
React Hook Formβ
Use the Autocomplete component together with the React Hook Form. To do this, install this dependency in the project:
yarn add react-hook-form
import React, { useState } from 'react';
import { useForm, Controller } from 'react-hook-form';
import {
Form,
Autocomplete,
Text,
Button
} from '@resultadosdigitais/tangram-components';
export default function WithReactHookForm() {
const [submitted, onSubmit] = useState(false);
const currencies = [
{ value: 'BRL', label: 'Real' },
{ value: 'USD', label: 'Dolar' },
{ value: 'EUR', label: 'Euro' }
];
const {
control,
setValue,
handleSubmit,
formState: { errors }
} = useForm();
const CURRENCY = 'currency';
const handleFieldChange = field => (_, option) => {
field.onChange(option);
};
const handleClear = () => {
setValue(CURRENCY, null);
};
return (
<>
{submitted && (
<Text>
<strong>Submitted: </strong>
<code>{JSON.stringify(submitted)}</code>
</Text>
)}
<Form onSubmit={handleSubmit(onSubmit)}>
<Form.Label htmlFor={CURRENCY}>Currency</Form.Label>
<Form.Control error={Boolean(errors.currency)}>
<Controller
control={control}
name={CURRENCY}
defaultValue={null}
render={({ field }) => (
<Autocomplete
id={CURRENCY}
name={CURRENCY}
options={currencies}
placeholder="Select currency"
renderNoOption="No currency found"
aria-describedby={`${CURRENCY}-feedback`}
onChange={handleFieldChange(field)}
onClear={handleClear}
/>
)}
rules={{ required: true }}
/>
{errors.currency && (
<Form.Feedback id={`${CURRENCY}-feedback`}>
This field is required
</Form.Feedback>
)}
</Form.Control>
<Button type="submit">Submit</Button>
</Form>
</>
);
}
See and test the full example below: