Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Delete item from state array in react

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.
by

3 Answers

akshay1995
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});
}
},
sandhya6gczb
Easy Way To Delete Item From state array in react:

when any data delete from database and update list without API calling that time you pass deleted id to this function and this function remove deleted recored from list

export default class PostList extends Component {
this.state = {
postList: [
{
id: 1,
name: 'All Items',
}, {
id: 2,
name: 'In Stock Items',
}
],
}


remove_post_on_list = (deletePostId) => {
this.setState({
postList: this.state.postList.filter(item => item.post_id != deletePostId)
})
}

}
pankajshivnani123
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
})});
}

Login / Signup to Answer the Question.