Reputation: 335
I was playing with Material UI autocomplete component's github label picker example and modified it as per sandbox below: https://codesandbox.io/s/material-demo-hwi3l?file=/demo.js
The Autocomplete works fine. When I select company names from the list they show up as chip elements after closing and when I deselect them individually, they get hidden as well. However, I am unable to figure out how to delete individual elements by clicking on chip's close button. I am unable to figure out what exactly to put in the chip's onDelete prop?
{
value.map((company, index) => (
<Chip
label={company.name}
onDelete={(event, newValue) => {
//setPendingValue(company);
}}
color="primary"
className={classes.selectedCompanies}
/>
))
}
Since the Chip as per sandbox is inside the value array, I am not sure how I could delete something from inside it while looping through it. Any help would be greatly appreciated.
Upvotes: 1
Views: 1757
Reputation: 5016
One way to delete from an array is to filter where each iterated item is not the deletable item. Doing so returns a new array that omits the deletable item. So in your example:
The delete-handler:
const handleDelete = name => {
const newValue = value.filter(company => company.name !== name);
setValue(newValue);
};
The chip element:
{value.map((company) => (
<Chip
key={company.name}
label={company.name}
onDelete={() => handleDelete(company.name)}
The codesandbox with the solution
Note, in React, you should include the iterated key in each list item.
Upvotes: 2