Reputation: 1141
How to disable the selected option in the list of options in autocomplete MUI?
For example, after selecting option "b", it should be disabled.
import Autocomplete from "@material-ui/lab/Autocomplete";
import { TextField } from "@material-ui/core";
function App() {
return (
<Autocomplete
freeSolo
id="free-solo-demo"
options={["a", "b", "c"]}
renderInput={params => (
<TextField
{...params}
label="freeSolo"
margin="normal"
variant="outlined"
fullWidth
/>
)}
/>
);
}
Upvotes: 0
Views: 1849
Reputation: 2869
You can achieve this using getOptionDisabled
prop. You just have to pass a function to this prop which says to disable the option if already been selected.
There is another prop available in this component called filterSelectedOptions
, which filters out the selected option.
You can find both of these working examples over here Stackblitz👈
const [selectedOptions, setSelectedOptions] = useState([]);
const options = ['a', 'b', 'c'];
<Autocomplete
multiple
freeSolo
options={options}
value={selectedOptions}
//disabling selected options
getOptionDisabled={(option) =>
selectedOptions.some((selectedOption) => selectedOption === option)
}
onChange={(_, value) => {
setSelectedOptions(value);
}}
renderInput={(params) => (
<TextField
{...params}
label="Multiple values"
placeholder="Favorites"
/>
)}
/>
Upvotes: 1