Mike Holzbach Mike Holzbach - 1 month ago 6
Javascript Question

.setState(): Filtering a person from an array of objects on button click

In the code below, I am trying to remove a person from what will eventually be an org chart when the delete button next to their name is clicked. At the moment, nothing happens. The closest I've come is all 5 people being deleted when any one of the delete buttons is clicked, but I only want the one person deleted who's button is clicked. I feel like I'm making more of a JS error than a React error.

See the full code sandbox here.

Any help would be appreciated, thank you!

import React from "react";
import { Component } from "react";

const list = [
{
name: "Person 1",
phone: "123-4567",
itemId: 11
},
{
name: "Person 2",
phone: "123-4567",
itemId: 12
},
{
name: "Person 3",
phone: "123-4567",
itemId: 23
},
{
name: "Person 4",
phone: "123-4567",
itemId: 34
},
{
name: "Person 5",
phone: "123-4567",
itemId: 45
}
];

class Entry extends Component {
constructor(props) {
super(props);

this.state = {
list: list
};
this.handleClick = this.handleClick.bind(this);
}

handleClick(e) {
this.setState({
list: this.state.list.filter(function(person) {
return person !== e.target.value;
})
});
}

render() {
return (
<div>
{this.state.list.map(item =>
<tr key={item.itemId}>
<td>
{item.name}
</td>
<td>
{item.phone}
</td>
<td>
<a className="delete" onClick={this.handleClick} />
</td>
</tr>
)}
</div>
);
}
}

export default Entry;

Answer Source

Your click event has no value, you can pass the itemId:

onClick={() => this.handleClick(item.itemId)}

Then your handleClick should look like:

handleClick(itemId) {
    this.setState({
      list: this.state.list.filter(function(person) {
        return person.itemId !== itemId;
      })
    });
  }

https://codesandbox.io/s/mo2l8z7469