React material Autocomplete: Prevent option deletion of some selected items

25 Views Asked by At

I have an Autocomplete where I preselect some values.

It is working fine.

My requirement is to not allow user delete preselected options from the Autocomplete.

I get may help mentioning getOptionsDisabled option but that is for making item non selectable.

But my requirement is to disable the item that is already selected so that user cannot deselect/remove it.

I can achieve it by doing some workaround on onChange event or any other event to prevent user from deleting it when user press the delete, but that is not so user friendly and also not that clear by looking to the autocomplete in a glance.

The disabled options makes the things clear immediately.

I could not find any help anywhere to achieve this.

Is there any way to do that?

1

There are 1 best solutions below

0
Pawan Nogariya On

Found the way to acheive it!!

I am using renderTags method where I am creating tags with disabled true/false based on my condition like below to achieve this and it is working perfectly.

renderTags={(value: IDropdown[], getTagProps) =>
    value.map((option: any, index: number) => (
        declarationNilSections.findIndex(x => x.value === option.value) !== -1 ?
            (<Chip
                variant="filled"
                size="small"
                color="primary"
                label={option.label}
                disabled={true}
            />) :
            (<Chip
                variant="filled"
                size="small"
                color="primary"
                label={option.label}
                {...getTagProps({ index })}
            />)

    ))
}

For my particular requirement where I do not want to have user delete these preselected option by any means, I had do disable two more ways which can cause the options to be deleted.

  1. From backspace button press on the control
  2. By Autocomplete clear all options button

To achieve first point I disabled backspace button deletion from my Autocomplete input, so my renderInput function looks like this now

renderInput={(params) => (
    <TextField
        {...params}
        placeholder="Sections"
        label='Nil Sections'
        onKeyDown={(event: any) => {
            if (event.key === 'Backspace') {
                event.stopPropagation();
            }
        }
        }
    />

And finally to disable clear all options button from Autocomplete, I added this to the Autocomplete properties

disableClearable={true}

And bingo!! I have everything working now as per my requirement.