React Material-UI Autocomplete. How to get value of deleted option?

Viewed 1413

I have a Autocomplete multiple select element. When I click on cross, to delete some option, I want to get this value. I tried to use ChipProps = {{onDelete: some function}} but it did not work :( I get undefined, and more over, delete function stops to work at all. Here is my code

const top100Films = [
    { title: 'The Shawshank Redemption', year: 1994 },
    { title: 'The Godfather', year: 1972 },
    { title: 'The Godfather: Part II', year: 1974 },
    { title: 'The Dark Knight', year: 2008 },
    { title: '12 Angry Men', year: 1957 },
    { title: "Schindler's List", year: 1993 },
];

<Autocomplete
    multiple
    id="tags-standard1"
    options={top100Films}
    getOptionLabel={(option) => option.title}
    //ChipProps = {{onDelete: (option) => {console.log(option.title)}}} 
    renderInput={(params) => (
        <TextField
            {...params}
            size="small"
            variant="outlined"
            label="Films"
        />
    )}
/>

So could anybody tell me how to get Id, or value, of deleted option?

3 Answers

I can confirm the deletion stops working if you add onDelete handler in ChipProps. I believe that it's a bug from Material-UI side. In the meantime you probably want to use the following hack to get the value of the chip when deleted:

<Autocomplete
  multiple
  options={top100Films}
  fullWidth
  getOptionLabel={(option) => option.title}
  onChange={(e, option, reason) => {
    if (reason === "remove-option") {
      console.log("delete", e.currentTarget.parentElement.innerText);
    }
    if (reason === "clear") {
      console.log("clear all");
    }
  }}
  {...}
/>

Live Demo

Edit 64334724/react-material-ui-autocomplete-how-to-get-value-of-deleted-option

onChange={(e, value, situation, option) => {
          if (situation === "removeOption") {

           //write your code here
            console.log("--->", e, value, situation, option);
          }
          setReceivers((state) => value);
        }}

now it's removeOption not remove-option

Related