Laboratory for new Material UI modules - hosts incubator components that are not yet ready to move to core
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
React hook providing autocomplete functionality with filtering, selection management, and keyboard navigation support. This hook is re-exported directly from @mui/material/useAutocomplete for convenience and backward compatibility.
Core autocomplete functionality hook that manages state, filtering, and selection for autocomplete components. Note: This is a direct re-export from @mui/material/useAutocomplete - refer to Material-UI Autocomplete documentation for the complete API specification.
/**
* Hook providing autocomplete functionality for input components
* @param props - Autocomplete configuration options
* @returns Autocomplete state and event handlers
*/
function useAutocomplete<T>(props: UseAutocompleteProps<T>): UseAutocompleteReturnValue<T>;
interface UseAutocompleteProps<T> {
/** Array of options to display in autocomplete */
options: T[];
/** Default selected value(s) */
defaultValue?: T | T[];
/** Controlled selected value(s) */
value?: T | T[];
/** Callback when selection changes */
onChange?: (event: React.SyntheticEvent, value: T | T[] | null, reason: string) => void;
/** Callback when input value changes */
onInputChange?: (event: React.SyntheticEvent, value: string, reason: string) => void;
/** Enable multiple selections (default: false) */
multiple?: boolean;
/** Disable the input (default: false) */
disabled?: boolean;
/** Disable clearing the input (default: false) */
disableClearable?: boolean;
/** Include input in options (default: false) */
includeInputInList?: boolean;
/** Function to get option label for display */
getOptionLabel?: (option: T) => string;
/** Function to determine if option is selected */
isOptionEqualToValue?: (option: T, value: T) => boolean;
/** Function to determine if option is disabled */
getOptionDisabled?: (option: T) => boolean;
/** Filter function for options */
filterOptions?: (options: T[], params: { inputValue: string; getOptionLabel: (option: T) => string }) => T[];
/** Maximum number of tags to show when multiple (default: -1) */
limitTags?: number;
/** Open state of the listbox */
open?: boolean;
/** Callback when open state changes */
onOpen?: (event: React.SyntheticEvent) => void;
/** Callback when listbox closes */
onClose?: (event: React.SyntheticEvent, reason: string) => void;
}
interface UseAutocompleteReturnValue<T> {
/** Props for the root element */
getRootProps: () => object;
/** Props for the input element */
getInputProps: () => object;
/** Props for the input label element */
getInputLabelProps: () => object;
/** Props for the listbox element */
getListboxProps: () => object;
/** Function to get props for option elements */
getOptionProps: (props: { option: T; index: number }) => object;
/** Current input value */
inputValue: string;
/** Currently selected value(s) */
value: T | T[];
/** Whether the popup is open */
popupOpen: boolean;
/** Whether the component is focused */
focused: boolean;
/** Anchor element for popup positioning */
anchorEl: HTMLElement | null;
/** Function to set anchor element */
setAnchorEl: (el: HTMLElement | null) => void;
/** Currently highlighted option index */
focusedTag: number;
/** Filtered options to display */
groupedOptions: T[];
}Usage Example:
import React from 'react';
import { useAutocomplete } from '@mui/lab';
import { TextField, Autocomplete } from '@mui/material';
// Basic autocomplete with string options
function BasicAutocomplete() {
const options = ['Option 1', 'Option 2', 'Option 3'];
const {
getRootProps,
getInputProps,
getListboxProps,
getOptionProps,
groupedOptions,
popupOpen
} = useAutocomplete({
options,
getOptionLabel: (option) => option
});
return (
<div {...getRootProps()}>
<TextField {...getInputProps()} />
{popupOpen && (
<ul {...getListboxProps()}>
{groupedOptions.map((option, index) => (
<li {...getOptionProps({ option, index })} key={index}>
{option}
</li>
))}
</ul>
)}
</div>
);
}
// Autocomplete with object options
interface Person {
id: number;
name: string;
email: string;
}
function PersonAutocomplete() {
const people: Person[] = [
{ id: 1, name: 'John Doe', email: 'john@example.com' },
{ id: 2, name: 'Jane Smith', email: 'jane@example.com' },
];
const autocomplete = useAutocomplete({
options: people,
getOptionLabel: (person) => person.name,
isOptionEqualToValue: (option, value) => option.id === value.id,
onChange: (event, value) => {
console.log('Selected person:', value);
}
});
return (
<div {...autocomplete.getRootProps()}>
<TextField
{...autocomplete.getInputProps()}
label="Select Person"
/>
{autocomplete.popupOpen && (
<ul {...autocomplete.getListboxProps()}>
{autocomplete.groupedOptions.map((person, index) => (
<li {...autocomplete.getOptionProps({ option: person, index })} key={person.id}>
<div>
<strong>{person.name}</strong>
<div style={{ fontSize: '0.8em', color: 'gray' }}>
{person.email}
</div>
</div>
</li>
))}
</ul>
)}
</div>
);
}Utility function for creating custom filter functions with built-in fuzzy matching and configuration options.
/**
* Create a filter function for autocomplete options
* @param options - Filter configuration options
* @returns Filter function for use with useAutocomplete
*/
function createFilterOptions<T>(options?: FilterOptionsConfig<T>): FilterOptions<T>;
interface FilterOptionsConfig<T> {
/** Whether to ignore case when filtering (default: true) */
ignoreCase?: boolean;
/** Whether to ignore diacritics/accents (default: true) */
ignoreAccents?: boolean;
/** Where to match the input text (default: 'any') */
matchFrom?: 'any' | 'start';
/** Maximum number of suggestions to return (default: no limit) */
limit?: number;
/** Stringify function for complex objects */
stringify?: (option: T) => string;
/** Trim input before filtering (default: false) */
trim?: boolean;
}
type FilterOptions<T> = (
options: T[],
params: {
inputValue: string;
getOptionLabel: (option: T) => string;
}
) => T[];Usage Example:
import { useAutocomplete, createFilterOptions } from '@mui/lab';
// Custom filter with configuration
const filter = createFilterOptions({
matchFrom: 'start',
ignoreCase: true,
limit: 5
});
function CustomFilterAutocomplete() {
const options = ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry'];
const autocomplete = useAutocomplete({
options,
filterOptions: filter,
getOptionLabel: (option) => option
});
// ... render logic
}
// Filter for complex objects
interface Product {
id: number;
name: string;
category: string;
description: string;
}
const productFilter = createFilterOptions({
stringify: (product: Product) =>
`${product.name} ${product.category} ${product.description}`,
limit: 10
});
function ProductAutocomplete() {
const products: Product[] = [
{ id: 1, name: 'Laptop', category: 'Electronics', description: 'Gaming laptop' },
// ... more products
];
const autocomplete = useAutocomplete({
options: products,
getOptionLabel: (product) => product.name,
filterOptions: productFilter
});
// ... render logic
}function MultipleAutocomplete() {
const options = ['React', 'Vue', 'Angular', 'Svelte'];
const autocomplete = useAutocomplete({
options,
multiple: true,
getOptionLabel: (option) => option,
limitTags: 3,
onChange: (event, value) => {
console.log('Selected options:', value);
}
});
return (
<div {...autocomplete.getRootProps()}>
<TextField
{...autocomplete.getInputProps()}
label="Select Frameworks"
/>
{/* Display selected tags */}
<div>
{(autocomplete.value as string[]).map((tag, index) => (
<span key={index} style={{ margin: '2px', padding: '4px', background: '#e0e0e0' }}>
{tag}
</span>
))}
</div>
{/* Options list */}
{autocomplete.popupOpen && (
<ul {...autocomplete.getListboxProps()}>
{autocomplete.groupedOptions.map((option, index) => (
<li {...autocomplete.getOptionProps({ option, index })} key={index}>
{option}
</li>
))}
</ul>
)}
</div>
);
}While this hook is available in MUI Lab, it's recommended to use the complete Autocomplete component from @mui/material for most use cases:
// Recommended for most applications
import { Autocomplete, TextField } from '@mui/material';
function RecommendedAutocomplete() {
const options = ['Option 1', 'Option 2', 'Option 3'];
return (
<Autocomplete
options={options}
renderInput={(params) => <TextField {...params} label="Options" />}
onChange={(event, value) => console.log(value)}
/>
);
}The useAutocomplete hook is primarily useful when building custom autocomplete implementations or when you need more control over the rendering and behavior.