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:

  1. The option is not a duplicate of a selected option
  2. The option label matches the input value
The function returns only the options that meet both criteria, and these are the options that are shown in the Autocomplete suggestions.

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

Popular posts from this blog

Step-by-Step Tutorial: How to Backup and Restore MongoDB Databases 2023