I have an array of ingredients I want to display as a list in my React app. Associated with each item is a Delete
button that when clicked, would remove that specific element from the array and re-render with the updated array.
Is there a way to find the index of the element and pass it onto the handleDelete()
function?
Or is the only way to loop through all elements to find and remove?
handleDelete(id) {
//use id to remove element from the array
//setState of newly filtered array
}
render() {
var ingredients = ["chicken", "rice"]
return (
<ul className="pantry">
{
ingredients.map((ingred, index) => {
return <li key={ingred.index}><button onClick={this.handleDelete.bind(this, ingred.index)}>Delete</button>{ ingred }</li>
})
}
</ul>
);
}