Reputation: 4333
I'm trying to autocomplete the input when searched with either of the two values - title
and year
. However, it does only work when I search with title
. When I search with year
, it does not show any options.
Sample code
export default function ComboBox() {
return (
<Autocomplete
id="combo-box-demo"
options={top100Films}
getOptionLabel={(option) => option.title || option.year}
style={{ width: 300 }}
renderInput={(params) => (
<TextField {...params} label="Combo box" variant="outlined" />
)}
/>
);
}
I have created a working example using Code Sandbox
Could anyone please help?
Upvotes: 2
Views: 764
Reputation: 81006
One way to make this work is to make the year part of the option label:
/* eslint-disable no-use-before-define */
import React from "react";
import TextField from "@material-ui/core/TextField";
import Autocomplete from "@material-ui/lab/Autocomplete";
import { top100Films } from "./movies";
export default function ComboBox() {
return (
<Autocomplete
id="combo-box-demo"
options={top100Films}
getOptionLabel={(option) => `${option.title} (${option.year})`}
style={{ width: 300 }}
renderInput={(params) => (
<TextField {...params} label="Combo box" variant="outlined" />
)}
/>
);
}
If you don't want to display the year, but still want to match on it, the other way is to use the filterOptions
prop to customize the matching:
/* eslint-disable no-use-before-define */
import React from "react";
import TextField from "@material-ui/core/TextField";
import Autocomplete from "@material-ui/lab/Autocomplete";
import { createFilterOptions } from "@material-ui/lab/Autocomplete";
import { top100Films } from "./movies";
const filterOptions = createFilterOptions({
stringify: (option) => `${option.title} ${option.year}`
});
export default function ComboBox() {
return (
<Autocomplete
id="combo-box-demo"
filterOptions={filterOptions}
options={top100Films}
getOptionLabel={(option) => option.title}
style={{ width: 300 }}
renderInput={(params) => (
<TextField {...params} label="Combo box" variant="outlined" />
)}
/>
);
}
Related documentation: https://material-ui.com/components/autocomplete/#custom-filter
Upvotes: 5