How to delete an item from state array?

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.

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.

16 Answers
16

Leave a Comment