AutocompletePro
FormKit Pro Quick Installation Guide 🚀
The autocomplete input allows you to search through a list of options.
In React JSX props like selectionAppearance, loadOnCreated, and emptyMessage follow each framework's normal prop casing.
The options prop can accept three different formats of values:
- An array of objects with
valueandlabelkeys (see example above) - An array of strings
['A', 'B', 'C'] - An object literal with key-value pairs
{ a: 'A', b: 'B', c: 'C' } - A function that returns any of the above
If you assign options as an empty array, the input will be rendered in a disabled state.
Basic examples
Single-select
By default, the autocomplete input will render in single-select mode:
<FormKit type="form" actions={false}> {({ value }) => ( <> <FormKit type="autocomplete" name="country" label="Search for a country" placeholder="Example: United States" options={countries} popover /> <pre>{JSON.stringify(value, null, 2)}</pre> </> )}</FormKit>Multi-select
By setting the multiple prop the autocomplete input will render in multi-select mode:
<FormKit type="form" actions={false}> {({ value }) => ( <> <FormKit type="autocomplete" name="country" label="Search for a country" placeholder="Example: United States" options={countries} multiple popover /> <pre>{JSON.stringify(value, null, 2)}</pre> </> )}</FormKit>Notice in the example above that because the multiple prop is set, the value prop must be an array.
Filtering
The autocomplete input will filter options with its own internal search function. You can replace this search function by providing the filter prop a function of your own. Your function will receive two arguments, the option being iterated over and the current search value:
const customFilter = (option, search) => option.label.toLowerCase().startsWith((search || '').toLowerCase())<FormKit type="autocomplete" name="autocomplete" label="Search for a country" options={countries} placeholder="Example: United States" popover filter={customFilter}/>Dynamic options
Instead of passing a static list to the options prop, you can assign it to a function. Doing so is useful when you need to load options from an API or another source.
Search parameter
In this example, we'll assign the options prop the searchMovies function. By doing so, searchMovies will receive the context object as an argument. Within this context object is the search property, which is the current search value. To perform our search, we'll use the search value as the query parameter for our API request:
// Search movie receives FormKit's context object// which we are destructuring to get the search value.async function searchMovies({ search }) { if (!search) return [] const response = await fetch( `https://api.themoviedb.org/3/search/movie?query=${ search || '' }&api_key=f48bcc9ed9cbce41f6c28ea181b67e14&language=en-US&page=1&include_adult=false` ) if (response.ok) { const data = await response.json() // Iterating over results to set the required // `label` and `value` keys. return data.results.map((result) => ({ label: result.title, value: result.id, })) } // If the request fails, we return an empty array. return []}<FormKit name="movie" type="autocomplete" label="Search for your favorite movie" placeholder="Example: Shawshank Redemption" popover options={searchMovies}/>Page and hasNextPage parameters
A likely scenario you'll encounter is needing to search through a paginated API. This can be done by referencing the same context object as before. Within this object, we can utilize the page and hasNextPage properties. The page property is the current page number, and the hasNextPage property is a function to be called when there are more pages to load:
// Search movie receives FormKit's context object// which we are destructuring to get the search value,// the page, and the hasNextPage parameters.async function searchMovies({ search, page, hasNextPage }) { if (!search) return [] const response = await fetch( `https://api.themoviedb.org/3/search/movie?query=${ search || '' }&api_key=f48bcc9ed9cbce41f6c28ea181b67e14&language=en-US&page=${page}&include_adult=false` ) if (response.ok) { const data = await response.json() if (page !== data.total_pages) hasNextPage() return data.results.map((result) => ({ label: result.title, value: result.id, })) } return []}<FormKit name="movie" type="autocomplete" label="Search for your favorite movie" placeholder="Example: Lord of the Rings" options={searchMovies} popover/>Option loader
Rehydrating values
FormKit's autocomplete input also provides an optionLoader prop that allows you to rehydrate values that are not in the options list. In this example, we'll provide the autocomplete an initial value (a movie ID), and assign the optionLoader to a function that will make a request to the API to get the movie:
// Search movie receives FormKit's context object// which we are destructuring to get the search value,// the page, and the hasNextPage parameters.async function searchMovies({ search, page, hasNextPage }) { if (!search) return [] const response = await fetch( `https://api.themoviedb.org/3/search/movie?query=${ search || '' }&api_key=f48bcc9ed9cbce41f6c28ea181b67e14&language=en-US&page=${page}&include_adult=false` ) if (response.ok) { const data = await response.json() if (page !== data.total_pages) hasNextPage() return data.results.map((result) => ({ label: result.title, value: result.id, })) } return []}// The function assigned to the `optionLoader` prop will be called with the// value of the option as the first argument (in this case, the movie ID), and// the cached option as the second argument (if it exists).async function loadMovie(id, cachedOption) { if (cachedOption) return cachedOption const response = await fetch( `https://api.themoviedb.org/3/movie/${id}?api_key=f48bcc9ed9cbce41f6c28ea181b67e14&language=en-US` ) if (response.ok) { const data = await response.json() return { label: data.title, value: data.id, } } return { label: 'Error loading' }}<FormKit type="form" actions={false}> {({ value }) => ( <> <FormKit name="movie" type="autocomplete" label="Search for your favorite movie" placeholder="Example: Harry Potter" options={searchMovies} defaultValue={597} optionLoader={loadMovie} popover /> <pre>{JSON.stringify(value, null, 2)}</pre> </> )}</FormKit>Notice in the example above that the optionLoader function is passed two arguments: the value of the selected option (in this case, the movie ID) and the cachedOption. The cachedOption prop is used for preventing unnecessary lookups. If the cachedOption is not null it means that the selected option has already been loaded, and you can return the cachedOption directly.
Loading Style
Instead of requiring your users to click the Load more button to load additional options, you can set the loadOnScroll prop to true, which will paginate options as you scroll to the bottom of the options list.
Load on created
If you would rather load options when the autocomplete is created, you can set the load-on-created prop to true, and our function, loadCurrentlyPopularMovies will be called without the user needing to expand the listbox:
// Search movie receives FormKit's context object// which we are destructuring to get the search value.async function searchMovies({ search }) { await new Promise((resolve) => setTimeout(resolve, 1000)) if (!search) { // With no search value, lets just return a list of common movies. return [ { label: 'Saving Private Ryan', value: 857 }, { label: 'Everything Everywhere All at Once', value: 545611 }, { label: 'Gone with the Wind', value: 770 }, ] } const response = await fetch( `https://api.themoviedb.org/3/search/movie?query=${ search || '' }&api_key=f48bcc9ed9cbce41f6c28ea181b67e14&language=en-US&page=1&include_adult=false` ) if (response.ok) { const data = await response.json() // Iterating over results to set the required // `label` and `value` keys. return data.results.map((result) => ({ label: result.title, value: result.id, })) } // If the request fails, we return an empty array. return []}<FormKit type="form" actions={false}> {({ value }) => ( <> <FormKit name="movie" type="autocomplete" label="Search for your favorite movie" placeholder="Example: Shawshank Redemption" options={searchMovies} loadOnCreated popover /> <pre>{JSON.stringify(value, null, 2)}</pre> </> )}</FormKit>Option appearance
Option slot
The autocomplete input allows you to customize the look and feel of each option by using the option slot. In this example, we are using the option slot to display each option's asset, logo, and name:
In React this is typically implemented with an option entry on the slots prop.
<FormKit type="autocomplete" name="autocomplete" label="Search for and select a car brand" placeholder="Example: Toyota" options={carBrands} selectionAppearance="option" popover slots={{ option: ({ option }) => ( <div className="flex items-center"> <img src={option.logo} alt={`${option.label} logo`} className="mr-2 h-5 w-5" /> <span>{option.label}</span> </div> ), }}/>Selection appearance
The autocomplete input allows you to customize the look and feel of the selected option.
Selection appearance prop
The autocomplete input allows you to customize the look and feel of the selected option by using the selection-appearance prop. For either the single-select or multi-select
autocomplete, you can set the selection-appearance prop to text-input (default) or option:
<FormKit type="autocomplete" label="Single-select text input" placeholder="Pick a country" options={countries} popover defaultValue="FR"/><FormKit type="autocomplete" label="Single-select option" placeholder="Pick a country" options={countries} popover selectionAppearance="option" defaultValue="FR"/><FormKit type="autocomplete" label="Multiple text input" placeholder="Pick a country" options={countries} popover multiple defaultValue={['FR', 'GR', 'ES']}/><FormKit type="autocomplete" label="Multiple option" placeholder="Pick a country" options={countries} multiple selectionAppearance="option" defaultValue={['FR', 'GR', 'ES']}/>Selection slot
If you only want to customize the display of the selected option, set the selection appearance to option.
In React this is typically implemented with a selection entry on the slots prop.
<FormKit type="autocomplete" name="autocomplete" label="Search and select a car brand" placeholder="Example: Toyota" options={carBrands} popover selectionAppearance="option" defaultValue="audi" slots={{ selection: ({ option, classes }) => ( <div className={classes.selection}> <div className={`${classes.option} flex items-center`}> <img src={option.logo} alt={`${option.label} logo`} className="h-10 w-10 p-2" /> <span>{option.label}</span> </div> </div> ), }}/><FormKit type="autocomplete" name="autocomplete" label="Search and select a car brand" placeholder="Example: Toyota" options={carBrands} selectionAppearance="option" multiple defaultValue={['toyota', 'honda']} slots={{ selection: ({ option, classes }) => ( <div className={`${classes.selection} !p-0`}> <div className={`${classes.option} flex items-center`}> <img src={option.logo} alt={`${option.label} logo`} className="h-10 w-10 p-2" /> <span>{option.label}</span> </div> </div> ), }}/>
Audi
Toyota
HondaBehavioral props
Empty message
The autocomplete input, by default, will not expand the listbox when no search results are found while filtering. You can change this behavior by assigning the empty-message prop a message to display when no results are found:
<FormKit type="autocomplete" name="autocomplete" label="Search for a country" options={countries} placeholder="Example: United States" emptyMessage="No countries found" popover/>Close on select
If you would like the listbox to remain expanded after selecting a value, you can set close-on-select to false.
<FormKit type="autocomplete" name="autocomplete" label="Search for a country" options={countries} multiple closeOnSelect={false} placeholder="Example: United States" popover/>Reload on commit
If you want the options to be reloaded when the user commits a selection, use the reload-on-commit prop:
<FormKit type="autocomplete" name="country" label="Search for a country" placeholder="Example: United States" options={countries} reloadOnCommit closeOnSelect={false} multiple popover/>Open on click
To enable opening the autocomplete's listbox on click of its search input, set the open-on-click prop to true:
<FormKit type="autocomplete" name="country" label="Search for a country" placeholder="Example: United States" options={countries} openOnClick popover/>Open on focus
If you would like to open the autocomplete's listbox anytime the input is clicked, set the open-on-focus prop to true:
function focusAutocomplete() { document.getElementById('autocomplete')?.focus()}<FormKit type="button" onClick={focusAutocomplete}> Click me to focus autocomplete</FormKit><FormKit id="autocomplete" type="autocomplete" name="framework" label="Choose a frontend framework" placeholder="Example placeholder" options={frameworks} openOnFocus popover/>If open-on-focus is used, open-on-click will implicitly be set.
Clear search on open
For single-select autocompletes only, if you would like to clear the search input when the listbox is opened, set the clear-search-on-open:
<FormKit type="form" actions={false}> {({ value }) => ( <> <FormKit type="autocomplete" name="country" label="Search for a country" placeholder="Example: United States" options={countries} clearSearchOnOpen defaultValue="US" popover /> <pre>{JSON.stringify(value, null, 2)}</pre> </> )}</FormKit>Selection removable
For a single-select autocomplete, you can set the selection-removable prop. When set to true, a remove button will be displayed next to the selected option. This prop is by default set to true for autocompletes with selection appearance of option.
The selection-removable prop cannot be used for multi-selects.
<FormKit type="form" actions={false}> {({ value }) => ( <> <FormKit type="autocomplete" name="country" label="Search for a country" placeholder="Example: United States" options={countries} defaultValue="US" popover selectionRemovable /> <pre>{JSON.stringify(value, null, 2)}</pre> </> )}</FormKit>Open on remove
If you want the listbox to expand when an selection is removed, use the open-on-remove prop:
<FormKit type="form" actions={false}> {({ value }) => ( <> <FormKit type="autocomplete" name="country" label="Search for a country" placeholder="Example: United States" options={countries} openOnRemove selectionRemovable popover defaultValue="US" /> <pre>{JSON.stringify(value, null, 2)}</pre> </> )}</FormKit>Max
If you would like to limit the number of options that can be selected, you can use the max prop:
<FormKit type="autocomplete" label="Autocomplete (option appearance) with max prop set to 2" options={countries} selectionAppearance="option" multiple popover max="2"/><FormKit type="autocomplete" label="Autocomplete (text-input appearance) with max prop set to 2" options={countries} selectionAppearance="text-input" multiple popover max="2"/>Full example
Now let's combine what we've learned so far by leveraging the option slot for custom markup, and setting the options prop to a function that will return pages of movies from an API:
// Search movie receives FormKit's context object// which we are destructuring to get the search value,// the page, and the hasNextPage parameters.async function searchMovies({ search, page, hasNextPage }) { if (!search) { // When there is no search value we return a static list of top movies. return topMovies } const response = await fetch( `https://api.themoviedb.org/3/search/movie?query=${ search || '' }&api_key=f48bcc9ed9cbce41f6c28ea181b67e14&language=en-US&page=${page}&include_adult=false` ) if (response.ok) { const data = await response.json() if (page !== data.total_pages) hasNextPage() return data.results.map((result) => ({ label: result.title, value: result.id, poster_path: result.poster_path, overview: result.overview, })) } return []}<FormKit type="form" actions={false}> {({ value }) => ( <> <FormKit name="movie" type="autocomplete" label="Search for your favorite movie" placeholder="Example placeholder" options={searchMovies} selectionAppearance="option" multiple popover removeSelectionClass="p-2 pl-0" slots={{ option: ({ option }) => ( <div className="flex items-center justify-between"> <div className="mr-2 w-1/4"> <img src={`https://image.tmdb.org/t/p/w500${option.poster_path}`} alt="optionAvatar" className="w-full" /> </div> <div className="w-full"> <div className="text-base font-bold leading-none"> {option.label} </div> <p className="text-xs">{option.overview}</p> </div> </div> ), }} /> <pre>{JSON.stringify(value, null, 2)}</pre> </> )}</FormKit>Props & Attributes
| Prop | Type | Default | Description |
|---|---|---|---|
debounce | number | 200 | Number of milliseconds to debounce calls to an options function. |
options | any | [] | The list of options the user can select from. |
load-on-scroll | boolean | false | When set to true, the autocomplete will try loading more options based on the end-user`s scroll position |
selection-appearance | string | text-input | Changes the way the option label is display. |
multiple | boolean | false | Allows for multiple selections. |
open-on-click | boolean | false | The autocomplete is expanded upon focus of the input, as opposed to waiting to expand until a search value is entered. |
filter | function | null | Used to apply your own custom filter function for static options. |
option-loader | function | null | Used for hydrating initial value, or performing an additional request to load more information of a selected option. |
empty-message | string | undefined | Renders a message when there are no options to display. |
max | number | undefined | Limits the number of options that can be selected. |
open-on-remove | boolean | false | When the selection-removable prop is set to true, the autocomplete will not open after the selected value is removed. You can change this behavior by setting the open-on-remove prop to true. |
open-on-focus | boolean | false | |
options-appearance | string | undefined | For multi-select autocompletes, this prop allows you to customize the look and feel of the selected options. Possible values are default (the default) or checkbox. |
always-load-on-open | boolean | true | Determines whether the autocomplete should always load its options when opened or whether it should reference the options that were previously found when opening. |
load-on-created | boolean | false | When set to true, the autocomplete will load the options when the node is created. |
clear-search-on-open | boolean | false | When set to true, the search input will be cleared when the listbox is opened. |
max | number | string | undefined | If you would like to limit the number of options that can be selected, you can use the max prop (applies only to multi-select). |
popover | boolean | false | Renders the input's listbox using the browser Popover API. |
| Show Universal props | |||
config | Object | {} | Configuration options to provide to the input’s node and any descendent node of this input. |
delay | Number | 20 | Number of milliseconds to debounce an input’s value before the commit hook is dispatched. |
dirtyBehavior | string | touched | Determines how the "dirty" flag of this input is set. Can be set to touched or compare — touched (the default) is more performant, but will not detect when the form is once again matching its initial state. |
errors | Array | [] | Array of strings to show as error messages on this field. |
help | String | '' | Text for help text associated with the input. |
id | String | input_{n} | The unique id of the input. Providing an id also allows the input’s node to be globally accessed. |
ignore | Boolean | false | Prevents an input from being included in any parent (group, list, form etc). Useful when using inputs for UI instead of actual values. |
index | Number | undefined | Allows an input to be inserted at the given index if the parent is a list. If the input’s value is undefined, it inherits the value from that index position. If it has a value it inserts it into the lists’s values at the given index. |
label | String | '' | Text for the label element associated with the input. |
name | String | input_{n} | The name of the input as identified in the data object. This should be unique within a group of fields. |
parent | FormKitNode | contextual | By default the parent is a wrapping group, list or form — but this props allows explicit assignment of the parent node. |
prefix-icon | String | '' | Specifies an icon to put in the prefixIcon section. |
preserve | Boolean | false | Preserves the value of the input on a parent group, list, or form when the input unmounts. |
preserve-errors | Boolean | false | By default errors set on inputs using setErrors are automatically cleared on input, setting this prop to true maintains the error until it is explicitly cleared. |
sections-schema | Object | {} | An object of section keys and schema partial values, where each schema partial is applied to the respective section. |
suffix-icon | String | '' | Specifies an icon to put in the suffixIcon section. |
type | String | text | The type of input to render from the library. |
validation | String, Array | [] | The validation rules to be applied to the input. |
validation-visibility | String | blur | Determines when to show an input's failing validation rules. Valid values are blur, dirty, and live. |
validation-label | String | {label prop} | Determines what label to use in validation error messages, by default it uses the label prop if available, otherwise it uses the name prop. |
validation-rules | Object | {} | Additional custom validation rules to make available to the validation prop. |
value | Any | undefined | Seeds the initial value of an input and/or its children. Not reactive. Can seed entire groups (forms) and lists.. |
Sections & slot data
You can target a specific section of an input using that section's "key", allowing you to modify that section's classes, HTML (via :sections-schema, or content (via slots)). Read more about sections here.
The autocomplete's structure changes depending on a few different scenarios:
- Whether
selection-appearancehas been set totext-input(the default) oroption. - Whether multiple selections are enabled via the
multipleattribute.
Selection appearance text-input
When selection-appearance="text-input" (the default), the selected value(s) appear as comma-separated text in the input field.
Click on a section to lock focus to the chosen section. Click locked section again to unlock.
Selection appearance option
When selection-appearance="option", the selected value(s) render as styled chips. For single-select, the selections section appears inside inner. For multi-select, it appears inside wrapper below inner.
Click on a section to lock focus to the chosen section. Click locked section again to unlock.
Listbox (dropdown) structure
The listbox section contains the dropdown options. It is rendered inside a dropdownWrapper that handles positioning.
Click on a section to lock focus to the chosen section. Click locked section again to unlock.
| Section-key | Description |
|---|---|
selector | The selector section is a button element that opens the dropdown options list. |
selections | Contains individual selection sections. |
selection | Contains the selected option. |
listitem | A list item element that contains the option section. |
option | A div that contains the option content. |
listbox | The listbox section is a ul element that contains the options list. |
dropdownWrapper | Wraps the listbox section. A div that handles scrolling the listbox. |
optionLoading | A span element that is conditionally rendered within the selected option when loading is occurring. |
loaderIcon | An element for outputting an icon in the selector element when loading is occurring. |
selectIcon | An element for outputting an icon in the selector element when the dropdown is closed. |
loadMore | A list item element that is conditionally rendered at the bottom of the options list when there are more pages to load. |
loadMoreInner | A span element that acts as a wrapper for the loaderIcon within the loadMore section. |
removeSelection | A button element used for removing a specific selection. |
closeIcon | An element for outputting an icon within the removeSelection button. |
listboxButton | A button element that is used to open the dropdown. |
emptyMessage | A list item element that is conditionally rendered when there are no options to display. |
emptyMessageInner | A span element that acts as a wrapper for the emptyMessage section. |
| Show Universal section keys | |
outer | The outermost wrapping element. |
wrapper | A wrapper around the label and input. |
label | The label of the input. |
prefix | Has no output by default, but allows content directly before an input element. |
prefixIcon | An element for outputting an icon before the prefix section. |
inner | A wrapper around the actual input element. |
suffix | Has no output by default, but allows content directly after an input element. |
suffixIcon | An element for outputting an icon after the suffix section. |
input | The input element itself. |
help | The element containing help text. |
messages | A wrapper around all the messages. |
message | The element (or many elements) containing a message — most often validation and error messages. |
Accessibility
All FormKit inputs are designed with the following accessibility considerations in mind. Help us continually improve accessibility for all by filing accessibility issues here:
- Semantic markup
- ARIA attributes
- Keyboard accessibility
- Focus indicators
- Color contrast with the provided theme
- Accessible labels, help text, and errors
Accessibility attributes
| Section Key | Attribute | Value | Description |
|---|---|---|---|
input | tabindex | -1 or 0 | Prioritizes keyboard focus order by setting it to -1 when disabled and 0 when enabled. |
role | combobox | Indicates to assistive technologies that this element functions as a combobox. | |
readonly | Restrict user edits, ensuring data integrity and a controlled, informative user experience. | ||
aria-autocomplete | list | Guides input suggestions, presenting a collection of values that could complete the user's input. | |
aria-activedescendant | Manage focus to the current active descendent element. | ||
aria-expanded | Conveys the expandable state when the element is in focus. | ||
aria-controls | Associates the listbox element, with this element. | ||
listboxButton | tabindex | -1 or 0 | Prioritizes keyboard focus order by setting it to -1 when disabled and 0 when enabled. |
role | button | Indicates to assistive technologies that this element functions as a button. | |
aria-haspopup | true | Signals that an element triggers a pop-up or menu | |
aria-expanded | Conveys the expandable state when the element is in focus. | ||
aria-controls | Associates the listbox element, with this element. | ||
aria-disabled | Communicates the disabled state when the input is disabled. | ||
selectionWrapper | tabindex | -1 or 0 | Prioritizes keyboard focus order by setting it to -1 when disabled and 0 when enabled. |
selections | aria-live | polite | Communicates dynamic content changes when selections are on the screen. |
removeSelection | tabindex | -1 | Removes the prioritization of keyboard focus on this element. |
aria-controls | Associates the input element, with this element. | ||
| Universal Accessibility Attributes | |||
label | label | for | Associates a label to an input element. Users can click on the label to focus the input or to toggle between states. |
input | input | disabled | Disables an HTML element, preventing user interaction and signaling a non-interactive state. |
aria-describedby | Associates an element with a description, aiding screen readers. | ||
aria-required | Added when input validation is set to required. | ||
icon | icon | for | Links icon to input element when icon in rendered as a label. |
Keyboard Interactions
| Keyboard Event | Description |
|---|---|
| Enter | Opens the listbox when the input is focused. Selects an item when a list item is focused |
| Space | Opens the listbox when the input is focused. Selects an item when a list item is focused |
| Esc | Closes the listbox when the input is focused. |
| ↑ | Navigates to previous list item in list box. Closes listbox if most-previous item is selected |
| ↓ | Opens the listbox when input is focused. Navigates to next list item in list box. |
| Universal Keyboard Events | |
| Tab | Moves the focus to the next focusable element on the page. |
| Shift+Tab | Moves the focus to the previous focusable element on the page. |