Delete item from state array in react
When using React, you should never mutate the state directly. If an object (or Array
, which is an object too) is changed, you should create a new copy.
Others have suggested using Array.prototype.splice()
, but that method mutates the Array, so it's better not to use splice()
with React.
Easiest to use Array.prototype.filter()
to create a new array:
removePeople(e) {
this.setState({people: this.state.people.filter(function(person) {
return person !== e.target.value
})});
}
To remove an element from an array, just do:
array.splice(index, 1);
In your case:
removePeople(e) {
var array = [...this.state.people]; // make a separate copy of the array
var index = array.indexOf(e.target.value)
if (index !== -1) {
array.splice(index, 1);
this.setState({people: array});
}
},
Here is a minor variation on Aleksandr Petrov's response using ES6
removePeople(e) {
let filteredArray = this.state.people.filter(item => item !== e.target.value)
this.setState({people: filteredArray});
}