Skip to main content

AutocompleteField

The AutocompleteField behaves like a standard text input, with an additional panel of suggested options.

Import

// with @dhl-official/react-library:
import { DhlAutocompleteField } from "@dhl-official/react-library"
// with @dhl-official/ui-libraries/react-library:
import { DhlAutocompleteField } from "@dhl-official/ui-libraries/react-library"

Options to be displayed by the Autocomplete component are required and are to be passed to the options prop as an array.

options = [
{
id: "1",
label: "ARG",
value: "Argentina",
},
{
id: "2",
label: "AUS",
value: "Australia",
},
{
id: "3",
label: "GER",
value: "Germany",
},
];

Guidelines

  • By default, the AutoCompleteField component filters using the label field value within each option found in the options array. This behaviour occurs in the absence of a defined customFilter prop.
  • If you choose to omit the label field from your options array structure, you need to implement a custom filtering function, passed to the customFilter prop. There, you'll be able to specify upon which key to filter from your options object.
  • If your options list consists of an array of strings, the component internal business logic will convert it to a data structure that includes the label and value fields, assigning to both of them the same value.

Code

<DhlAutocompleteField options={[
{ id: "1", label: "ARG", value: "Argentina"},
{ id: "2", label: "AUS", value: "Australia"},
{ id: "3", label: "GER", value: "Germany" },
]}></DhlAutocompleteField>

Interactive Demo

Migrating from DUIL 1.0

  • Rename onBlur to blurEvent
  • Rename onChange to inputEvent
  • Rename onOptionSelected to optionSelected
  • Rename ariaDescribe to dataAriaDescribedby
  • Remove renderOption
  • Remove isBlock

Readme

Usage

Dhl-autocomplete-field

Snippets of code in HTML and JavaScript to show some of the use cases for the component. The code is not meant to be executed, but to be used as a reference for the usage of the component.
Angular, React and Vue usages are not included in this documentation, but can be easily derived from the html and javascript code.

default usage with custom event and, default filter function and custom validation

<form novalidate>
<dhl-autocomplete-field
name="autocomplete"
value=""
></dhl-autocomplete-field>

<hr />

<dhl-button
type="reset"
variant="outline"
>reset</dhl-button
>
<dhl-button type="submit">submit</dhl-button>
</form>

<script type="module">
const form = document.querySelector("form");

const options = Array.from(Array(10).keys()).map((i) => ({
value: `opt${i}`,
label: `Option ${i}`,
id: `id${i}`,
}));

const autocomplete = document.querySelector("dhl-autocomplete-field");
autocomplete.options = [...options];

const checkAutocompleteFieldValidity = async () => {
const validationMessageInvalid = "This field is NOT valid";
const validationMessageValid = "This field valid";

const isValid = await autocomplete.checkValidity();
autocomplete.validation = {
type: isValid ? Variants.valid : Variants.invalid,
message: isValid ? validationMessageValid : validationMessageInvalid,
};
};

autocomplete.addEventListener("dhlFocus", console.log);
autocomplete.addEventListener("dhlKeyUp", console.log);
autocomplete.addEventListener("dhlKeyDown", console.log);
autocomplete.addEventListener("dhlInput", console.log);

autocomplete.addEventListener("dhlBlur", async (e) => {
console.log(e);
await checkAutocompleteFieldValidity();
});

form.addEventListener("submit", async (e) => {
e.preventDefault();
await checkAutocompleteFieldValidity();

const data = new FormData(form);
console.log(Object.fromEntries(data));
});
</script>

usage with custom event, custom filter function and custom validation messages


<form novalidate>
<dhl-autocomplete-field
name="autocomplete"
value=""
></dhl-autocomplete-field>

<hr />

<dhl-button
type="reset"
variant="outline"
>reset</dhl-button
>
<dhl-button type="submit">submit</dhl-button>
</form>

<script type="module">
const form = document.querySelector("form");

const options = Array.from(Array(20).keys()).map((i) => ({
value: `opt${i}`,
label: `${i} option`,
id: `id${i}`,
}));

const autocomplete = document.querySelector("dhl-autocomplete-field");
autocomplete.options = [...options];

// custom filter example:
// only filter for values with at least 3 characters.
// if the user types "1 op" the options will be filtered
// to show only the options that contain "1 op" in the label
autocomplete.customFilter = (options, value) =>
value?.length < 3
? options
: options.filter((option) => option.label.includes(value));

const checkAutocompleteFieldValidity = async () => {
const validationMessageInvalid = "This field is NOT valid";
const validationMessageValid = "This field valid";

const isValid = await autocomplete.checkValidity();
autocomplete.validation = {
type: isValid ? Variants.valid : Variants.invalid,
message: isValid ? validationMessageValid : validationMessageInvalid,
};
};

autocomplete.addEventListener("dhlFocus", console.log);
autocomplete.addEventListener("dhlKeyUp", console.log);
autocomplete.addEventListener("dhlKeyDown", console.log);
autocomplete.addEventListener("dhlInput", console.log);

autocomplete.addEventListener("dhlBlur", async (e) => {
console.log(e);
await checkAutocompleteFieldValidity();
});

form.addEventListener("submit", async (e) => {
e.preventDefault();
await checkAutocompleteFieldValidity();

const data = new FormData(form);
console.log(Object.fromEntries(data));
});
</script>

Properties

PropertyAttributeDescriptionTypeDefault
blurEvent--[DEPRECATED] Use dhlBlur event instead.

An optional onBlur callback handler.
(event?: FocusEvent) => voidundefined
customFilter--An optional callback handler that accepts the options and input data, used for custom filtering. If this function is not passed, by default, filtering will happen on "label" key of the item if its an object or the actual value if the item is a primitive data type(options: unknown, value: string) => Option[]undefined
dataAriaDescribedbydata-aria-describedbyAn optional prop defining the list of reference IDs (separated by spaces), recommended when you want to an error message on your field.stringWhen autocomplete results are available use up and down arrows to review and enter to select. Touch device users, explore by touch or with swipe gestures.
dataAriaLabeldata-aria-labelAn optional prop defining the text read by the screen reader to represent the component; use this if you need different text to be read from label.stringundefined
dataClassNamedata-class-nameAn optional class name prop for the component.stringundefined
dataIdidAn optional prop. Gives a valid HTML ID attribute value for the component.stringdhl-autocomplete-field-${getRandomString()}
dataTestiddata-testidAn optional prop. The test id attached to the component as a data-testid attribute.stringundefined
inputEvent--[DEPRECATED] - Use dhlInput event instead

An optional onChange callback handler, used to hold the logic for filtering Autocomplete options -
(event: InputEvent) => voidundefined
isBlockis-block[DEPRECATED] An optional prop flag to control if the component is rendered as block or inline-block element.

booleanundefined
isDisableddisabledAn optional flag to define if the component is disabled.booleanfalse
namenameAn optional value to be set to the element HTML name attribute. It takes any valid value that can be used for the name attribute of an HTMLInputElement.string"autocomplete"
numberOfOptionsCopynumber-of-options-copyAn optional prop holding the number of options in Autocomplete to be read by screen readersstring"results available below"
openOnFocusopen-on-focusAn optional prop when set to true, the option list will be shown on input focus.booleanfalse
optionSelected--[DEPRECATED] - Use dhlOptionSelected event instead

An optional callback handler, used to handle "an option selected" event -
(option: Option) => voidundefined
options (required)--A REQUIRED Autocomplete options prop array which holds the available options to select within the Autocomplete component(string \| Option)[]undefined
requiredrequiredAn optional prop to flag the component as required within a form context.booleanundefined
searchIconsearch-iconAn optional prop flag to define if the search icon is displayed.booleanundefined
validation--An optional object to set-up a custom components validation state. Required Fields: type{ type: Variants.valid \| Variants.invalid \| Variants.note; message?: string; }undefined
valuevalueAn optional prop defining the value of the component which is taken when a form is submitted.stringundefined
variant--An optional prop to select a component design variant. Required Fields type{ label?: string; placeholder?: string; type: Variants.animated \| Variants.static; }undefined

Events

EventDescriptionType
dhlOptionSelectedEvent emitted when an option is selected.CustomEvent<any>

Methods

checkValidity() => Promise<boolean>

Checks the validity of the input field.

Returns

Type: Promise<boolean>

A promise that resolves to true if the input field is valid, otherwise false.

getInputElement() => Promise<HTMLInputElement>

Retrieves the input element asynchronously.

Returns

Type: Promise<HTMLInputElement>

A promise that resolves to the input element.

getValidationMessage() => Promise<string>

Retrieves the validation message for the input field.

Returns

Type: Promise<string>

A promise that resolves to a string representing the validation message.

reportValidity() => Promise<boolean>

Reports the validity of the input field.

Returns

Type: Promise<boolean>

A promise that resolves to a boolean indicating whether the input field is valid.

setValidity(validity: ValidityState, validationMessage?: string) => Promise<void>

Sets the validity state of the input field.

Parameters

NameTypeDescription
validityValidityState- The validity state to set.
validationMessagestring- An optional validation message to set.

Returns

Type: Promise<void>

A Promise that resolves when the validity state is set.

willValidate() => Promise<boolean>

Returns a promise that resolves to true if the element will successfully validate, or false otherwise.

Returns

Type: Promise<boolean>

A promise that resolves to a boolean value indicating whether the element will validate.

Dependencies

Depends on

Graph


Built by DHL User Interface Library Team!