How to prevent showing the selected options again in the Autocomplete suggestions ? (Material UI/React)
How to prevent showing the selected options again in the Autocomplete suggestions ?
Issue,
Ans.
Below the filterOptions function filters the options based on two criteria:
- The option is not a duplicate of a selected option
- The option label matches the input value
const options = users?.map((user) => ({
label: `${user?.firstName} ${user?.lastName} - ${user?.email}`,
value: user?.email,
// avatar: <Avatar alt={user?.firstName} src={API_BASE_URL + user?.avatar} />
})) ?? [];
{!formik.values.alumni && <Box>
<Autocomplete
multiple
id="tags-outlined"
options={options}
getOptionLabel={(option) => option?.label}
filterSelectedOptions
filterOptions={(options, { inputValue }) => {
const selectedValues = formik.values.guests.map((guest) => guest.value);
return options.filter((option) => {
const isDuplicate = selectedValues.includes(option.value);
const isMatch = option.label.toLowerCase().includes(inputValue.toLowerCase());
return !isDuplicate && isMatch;
});
}}
value={formik.values.guests} //set the initial value of the Autocomplete
component
onChange={(event, newValue) => {
formik.setFieldValue('guests', newValue); //set the value of the "guests"
field
}}
onBlur={formik.handleBlur}
inputValue={inputValue}
onInputChange={(event, newInputValue) => {
setInputValue(newInputValue);
}}
renderInput={(params) => (
<TextField
{...params}
variant="outlined"
label="Add guests"
/>
)}
/>
{formik.touched.guests && formik.errors.guests && <p style={{ color: 'red',
marginTop: '5px', marginBottom: '-15px' }}>{formik.errors.guests}</p>}
</Box>
}

Comments
Post a Comment