snippetjavascriptreactCritical
How to delete an item from state array?
Viewed 0 times
deleteitemfromstatehowarray
Problem
The story is, I should be able to put Bob, Sally and Jack into a box. I can also remove either from the box. When removed, no slot is left.
I now need to remove, say, "Bob". The new array would be:
Here is my react component:
Here I show you a minimal code as there is more to it (onClick etc). The key part is to delete, remove, destroy "Bob" from the array but
people = ["Bob", "Sally", "Jack"]I now need to remove, say, "Bob". The new array would be:
["Sally", "Jack"]Here is my react component:
...
getInitialState: function() {
return{
people: [],
}
},
selectPeople(e){
this.setState({people: this.state.people.concat([e.target.value])})
},
removePeople(e){
var array = this.state.people;
var index = array.indexOf(e.target.value); // Let's say it's Bob.
delete array[index];
},
...Here I show you a minimal code as there is more to it (onClick etc). The key part is to delete, remove, destroy "Bob" from the array but
removePeople() is not working when called. Any ideas? I was looking at this but I might be doing something wrong since I'm using React.Solution
To remove an element from an array, just do:
In your case:
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});
}
},Code Snippets
array.splice(index, 1);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});
}
},Context
Stack Overflow Q#36326612, score: 300
Revisions (0)
No revisions yet.