or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

autocomplete.mddeprecated-components.mdindex.mdmasonry.mdtabs.mdtimeline.md

autocomplete.mddocs/

0

# Autocomplete Hook

1

2

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.

3

4

## Capabilities

5

6

### useAutocomplete Hook

7

8

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](https://mui.com/material-ui/react-autocomplete/) for the complete API specification.

9

10

```typescript { .api }

11

/**

12

* Hook providing autocomplete functionality for input components

13

* @param props - Autocomplete configuration options

14

* @returns Autocomplete state and event handlers

15

*/

16

function useAutocomplete<T>(props: UseAutocompleteProps<T>): UseAutocompleteReturnValue<T>;

17

18

interface UseAutocompleteProps<T> {

19

/** Array of options to display in autocomplete */

20

options: T[];

21

/** Default selected value(s) */

22

defaultValue?: T | T[];

23

/** Controlled selected value(s) */

24

value?: T | T[];

25

/** Callback when selection changes */

26

onChange?: (event: React.SyntheticEvent, value: T | T[] | null, reason: string) => void;

27

/** Callback when input value changes */

28

onInputChange?: (event: React.SyntheticEvent, value: string, reason: string) => void;

29

/** Enable multiple selections (default: false) */

30

multiple?: boolean;

31

/** Disable the input (default: false) */

32

disabled?: boolean;

33

/** Disable clearing the input (default: false) */

34

disableClearable?: boolean;

35

/** Include input in options (default: false) */

36

includeInputInList?: boolean;

37

/** Function to get option label for display */

38

getOptionLabel?: (option: T) => string;

39

/** Function to determine if option is selected */

40

isOptionEqualToValue?: (option: T, value: T) => boolean;

41

/** Function to determine if option is disabled */

42

getOptionDisabled?: (option: T) => boolean;

43

/** Filter function for options */

44

filterOptions?: (options: T[], params: { inputValue: string; getOptionLabel: (option: T) => string }) => T[];

45

/** Maximum number of tags to show when multiple (default: -1) */

46

limitTags?: number;

47

/** Open state of the listbox */

48

open?: boolean;

49

/** Callback when open state changes */

50

onOpen?: (event: React.SyntheticEvent) => void;

51

/** Callback when listbox closes */

52

onClose?: (event: React.SyntheticEvent, reason: string) => void;

53

}

54

55

interface UseAutocompleteReturnValue<T> {

56

/** Props for the root element */

57

getRootProps: () => object;

58

/** Props for the input element */

59

getInputProps: () => object;

60

/** Props for the input label element */

61

getInputLabelProps: () => object;

62

/** Props for the listbox element */

63

getListboxProps: () => object;

64

/** Function to get props for option elements */

65

getOptionProps: (props: { option: T; index: number }) => object;

66

/** Current input value */

67

inputValue: string;

68

/** Currently selected value(s) */

69

value: T | T[];

70

/** Whether the popup is open */

71

popupOpen: boolean;

72

/** Whether the component is focused */

73

focused: boolean;

74

/** Anchor element for popup positioning */

75

anchorEl: HTMLElement | null;

76

/** Function to set anchor element */

77

setAnchorEl: (el: HTMLElement | null) => void;

78

/** Currently highlighted option index */

79

focusedTag: number;

80

/** Filtered options to display */

81

groupedOptions: T[];

82

}

83

```

84

85

**Usage Example:**

86

87

```typescript

88

import React from 'react';

89

import { useAutocomplete } from '@mui/lab';

90

import { TextField, Autocomplete } from '@mui/material';

91

92

// Basic autocomplete with string options

93

function BasicAutocomplete() {

94

const options = ['Option 1', 'Option 2', 'Option 3'];

95

96

const {

97

getRootProps,

98

getInputProps,

99

getListboxProps,

100

getOptionProps,

101

groupedOptions,

102

popupOpen

103

} = useAutocomplete({

104

options,

105

getOptionLabel: (option) => option

106

});

107

108

return (

109

<div {...getRootProps()}>

110

<TextField {...getInputProps()} />

111

{popupOpen && (

112

<ul {...getListboxProps()}>

113

{groupedOptions.map((option, index) => (

114

<li {...getOptionProps({ option, index })} key={index}>

115

{option}

116

</li>

117

))}

118

</ul>

119

)}

120

</div>

121

);

122

}

123

124

// Autocomplete with object options

125

interface Person {

126

id: number;

127

name: string;

128

email: string;

129

}

130

131

function PersonAutocomplete() {

132

const people: Person[] = [

133

{ id: 1, name: 'John Doe', email: 'john@example.com' },

134

{ id: 2, name: 'Jane Smith', email: 'jane@example.com' },

135

];

136

137

const autocomplete = useAutocomplete({

138

options: people,

139

getOptionLabel: (person) => person.name,

140

isOptionEqualToValue: (option, value) => option.id === value.id,

141

onChange: (event, value) => {

142

console.log('Selected person:', value);

143

}

144

});

145

146

return (

147

<div {...autocomplete.getRootProps()}>

148

<TextField

149

{...autocomplete.getInputProps()}

150

label="Select Person"

151

/>

152

{autocomplete.popupOpen && (

153

<ul {...autocomplete.getListboxProps()}>

154

{autocomplete.groupedOptions.map((person, index) => (

155

<li {...autocomplete.getOptionProps({ option: person, index })} key={person.id}>

156

<div>

157

<strong>{person.name}</strong>

158

<div style={{ fontSize: '0.8em', color: 'gray' }}>

159

{person.email}

160

</div>

161

</div>

162

</li>

163

))}

164

</ul>

165

)}

166

</div>

167

);

168

}

169

```

170

171

### createFilterOptions

172

173

Utility function for creating custom filter functions with built-in fuzzy matching and configuration options.

174

175

```typescript { .api }

176

/**

177

* Create a filter function for autocomplete options

178

* @param options - Filter configuration options

179

* @returns Filter function for use with useAutocomplete

180

*/

181

function createFilterOptions<T>(options?: FilterOptionsConfig<T>): FilterOptions<T>;

182

183

interface FilterOptionsConfig<T> {

184

/** Whether to ignore case when filtering (default: true) */

185

ignoreCase?: boolean;

186

/** Whether to ignore diacritics/accents (default: true) */

187

ignoreAccents?: boolean;

188

/** Where to match the input text (default: 'any') */

189

matchFrom?: 'any' | 'start';

190

/** Maximum number of suggestions to return (default: no limit) */

191

limit?: number;

192

/** Stringify function for complex objects */

193

stringify?: (option: T) => string;

194

/** Trim input before filtering (default: false) */

195

trim?: boolean;

196

}

197

198

type FilterOptions<T> = (

199

options: T[],

200

params: {

201

inputValue: string;

202

getOptionLabel: (option: T) => string;

203

}

204

) => T[];

205

```

206

207

**Usage Example:**

208

209

```typescript

210

import { useAutocomplete, createFilterOptions } from '@mui/lab';

211

212

// Custom filter with configuration

213

const filter = createFilterOptions({

214

matchFrom: 'start',

215

ignoreCase: true,

216

limit: 5

217

});

218

219

function CustomFilterAutocomplete() {

220

const options = ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry'];

221

222

const autocomplete = useAutocomplete({

223

options,

224

filterOptions: filter,

225

getOptionLabel: (option) => option

226

});

227

228

// ... render logic

229

}

230

231

// Filter for complex objects

232

interface Product {

233

id: number;

234

name: string;

235

category: string;

236

description: string;

237

}

238

239

const productFilter = createFilterOptions({

240

stringify: (product: Product) =>

241

`${product.name} ${product.category} ${product.description}`,

242

limit: 10

243

});

244

245

function ProductAutocomplete() {

246

const products: Product[] = [

247

{ id: 1, name: 'Laptop', category: 'Electronics', description: 'Gaming laptop' },

248

// ... more products

249

];

250

251

const autocomplete = useAutocomplete({

252

options: products,

253

getOptionLabel: (product) => product.name,

254

filterOptions: productFilter

255

});

256

257

// ... render logic

258

}

259

```

260

261

### Multiple Selection

262

263

```typescript

264

function MultipleAutocomplete() {

265

const options = ['React', 'Vue', 'Angular', 'Svelte'];

266

267

const autocomplete = useAutocomplete({

268

options,

269

multiple: true,

270

getOptionLabel: (option) => option,

271

limitTags: 3,

272

onChange: (event, value) => {

273

console.log('Selected options:', value);

274

}

275

});

276

277

return (

278

<div {...autocomplete.getRootProps()}>

279

<TextField

280

{...autocomplete.getInputProps()}

281

label="Select Frameworks"

282

/>

283

{/* Display selected tags */}

284

<div>

285

{(autocomplete.value as string[]).map((tag, index) => (

286

<span key={index} style={{ margin: '2px', padding: '4px', background: '#e0e0e0' }}>

287

{tag}

288

</span>

289

))}

290

</div>

291

{/* Options list */}

292

{autocomplete.popupOpen && (

293

<ul {...autocomplete.getListboxProps()}>

294

{autocomplete.groupedOptions.map((option, index) => (

295

<li {...autocomplete.getOptionProps({ option, index })} key={index}>

296

{option}

297

</li>

298

))}

299

</ul>

300

)}

301

</div>

302

);

303

}

304

```

305

306

## Integration with Material-UI

307

308

While this hook is available in MUI Lab, it's recommended to use the complete `Autocomplete` component from `@mui/material` for most use cases:

309

310

```typescript

311

// Recommended for most applications

312

import { Autocomplete, TextField } from '@mui/material';

313

314

function RecommendedAutocomplete() {

315

const options = ['Option 1', 'Option 2', 'Option 3'];

316

317

return (

318

<Autocomplete

319

options={options}

320

renderInput={(params) => <TextField {...params} label="Options" />}

321

onChange={(event, value) => console.log(value)}

322

/>

323

);

324

}

325

```

326

327

The `useAutocomplete` hook is primarily useful when building custom autocomplete implementations or when you need more control over the rendering and behavior.