James
James

Reputation: 3815

Material-UI Autocomplete disable options present in array

I am trying to use the <Autocomplete /> Material-UI component as per their documentation.

Their example shows how to disable autocomplete by using the getOptionDisabled prop function as follows:

getOptionDisabled={option => option === timeSlots[0] || option === timeSlots[2]}

Let's say that I have an array that I am dynamically generating of timeSlots that I would like to disable, timeSlotsArr, how could I use this prop to exclude all options that are present inside the timeSlotsArr array?

My current code, which is not working, looks like this:

<Autocomplete
  options={timeSlots}
  getOptionDisabled={option => option === timeSlotsArr.indexOf(option}
  style={{ width: 300 }}
  renderInput={params => (
    <TextField
      {...params}
      label="Disabled options"
      variant="outlined"
      fullWidth
      inputProps={{
        ...params.inputProps,
        autoComplete: 'disabled', // disable autocomplete and autofill
      }}
    />
  )}
/>

Upvotes: 5

Views: 17400

Answers (2)

Sebasti&#225;n Ibarra
Sebasti&#225;n Ibarra

Reputation: 51

This worked for me

getOptionDisabled={(option) => !!timeSlotsArr.find(element => element === option)}

Upvotes: 3

David G.
David G.

Reputation: 1485

Wouldn't this be enough if you want to disable all the options in the dropdown?

getOptionDisabled={option => true}

As far as I understand you only pass a function that will return a boolean, so that would do it, right?

Also, your code is not working because it is comparing one of the options in the dropdown with what indexOf returns, which is -1 if it wasn't found, the index if it was. That is never going to be true. You could change it to:

getOptionDisabled={option => !!timeSlotsArr.find(option)}

If you use indexOf, the option would the index 0 would return false too, and you wouldn't want that.

Upvotes: 10

Related Questions