Josh
Josh

Reputation: 1

Material UI Autocomplete

I am building a form using Material UI's autocomplete feature. The field renders chips however I am unable to modify the onDelete prop of the chip component. I have tried modifying other props such as the variant, label, etc but even trying to get the onDelete prop to do a simple console log does not work. My code is below.

        <Autocomplete
      onChange={handleRecChange("foodRecs")}
      multiple
      options={menuItems}
      renderTags={(value, getTagProps) =>
        value.map((option, index) => (
          <Chip
            variant="outlined"
            key={option}
            label={option}
            onDelete={() => console.log("test")}
            {...getTagProps({ index })}
          />
        ))
      }
      renderInput={params => (
        <TextField
          {...params}
          variant="standard"
          label="Recommendations"
          placeholder="Choose anything from the menu"
          fullWidth
        />
      )}
    />

Upvotes: 0

Views: 6079

Answers (1)

Ido
Ido

Reputation: 5768

That's because you override onDelete in this line:

{...getTagProps({ index })}

getTagProps is a getter for the tag props. It includes onDelete function, since onDelete is a Chip property (you can print the getTagProps return value to see that).
You should placegetTagProps on the first line, to avoid unwanted prop overrides:

  <Chip
    {...getTagProps({ index })}
    variant="outlined"
    key={option}
    label={option}
    onDelete={() => console.log("test")}
  />

Upvotes: 4

Related Questions