Home > Mobile >  Ability to delete saved entries from a MUI AutoComplete free solo select box
Ability to delete saved entries from a MUI AutoComplete free solo select box

Time:12-03

I'm using the Autocomplete function with free solo entry in a React application for a search history type scenario. dropdown

Does anyone have any idea on how to manipulate the Autocomplete box to include such? Or even if Delete was pressed on the keyboard while hovering over an item. I just need to be able to pass the selected value to a custom function, and then I can sort out the details to edit the underlying data.

Here's a live example (without the ability to delete): https://6mmv9.csb.app/

And here's the code sandbox: https://codesandbox.io/s/mui-autocomplete-free-solo-6mmv9

CodePudding user response:

Here you can check out my forked version of your sandbox code: https://codesandbox.io/embed/mui-autocomplete-free-solo-forked-x83j2?fontsize=14&hidenavigation=1&theme=dark

In summary, few things I've changed are:

  1. I added renderOption prop to AutoComplete component like this to render delete icons:
renderOption={(props, option, state) => (
  <ListItem {...props}>
    <ListItemText primary={option} />
    <ListItemSecondaryAction>
      <IconButton
        edge="end"
        aria-label="delete"
        onClick={(e) => handleOptionDelete(option)}
      >
        <DeleteIcon />
      </IconButton>
    </ListItemSecondaryAction>
  </ListItem>
)}
  1. I wrote a function called handleOptionDelete that updates the local storage search history.
function App() {
  // ....

  const handleOptionDelete = (option) => {
    setSearchHistoryReference((state) => state.filter((opt) => opt !== option));
  };

  return (
    <div>
      <form noValidate autoComplete="off" onSubmit={handleSubmit}>
      // ....
  1. And ofcourse to add @material-ui/icons dependency so that we can use the DeleteIcon component.
  • Related