Reputation: 851
I'm using the Autocomplete function with free solo entry in a React application for a search history type scenario. https://v4.mui.com/components/autocomplete/#free-solo
The users' entries are recorded to their browser's local storage. That part is all working fine.
However, they want to keep this list clean - if they make a typo on a part number entry, for instance, they would like to be able to remove it from the saved list.
Here's what my code looks like:
<Autocomplete
freeSolo
className={classes.field}
value={reference}
onChange={(event, newValue) => {
setValue(newValue)
setReference(newValue)
}}
onInputChange={(event, newInputValue) => {
setValue(newInputValue)
}}
options={searchHistoryReference} // Array stored in local storage
renderInput={(params) => (
<TextField
{...params}
className={classes.field}
onChange={(e) => setReference(e.target.value)}
label='Number'
variant='outlined'
fullWidth
/>
)}
/>
Essentially, I'm thinking the most intuitive way would be to have an X or delete icon that could be pressed on an entry of the dropdown. Such as this:
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
Upvotes: 1
Views: 1539
Reputation: 523
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:
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>
)}
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}>
// ....
@material-ui/icons
dependency so that we can use the DeleteIcon
component.Upvotes: 2