I'm trying to figure out how to remove a row from a simple table using a simple button.
I try to use the index but with what I wrote, when I click on the line to delete, it is only all the others that are deleted ...
I guess the problem comes from the way I use the index but I have some difficulties to understand the behavior.
let users = [
{ firstName: "John", lastName: "Connor", age: 20 },
{ firstName: "Geralt", lastName: "Rivia", age: 45 },
{ firstName: "Nathan", lastName: "Drake", age: 36 }
]
class exercice extends React.Component {
constructor(props){
super(props);
this.state = {
users: users
}
}
onClickDeleteRow = index => {
users = users.splice(index,1)
this.setState({users: users})
console.log(this.state.users)
}
render() {
let usersName = this.state.users.map((user, index) => (
<tr key={index}>
<td>{user.firstName} </td>
<td>{user.lastName} </td>
<td><button onClick={() => this.onClickDeleteRow(index)}>Delete</button></td>
</tr>
))
return (
<table>
<thead>
<tr>
<th> firstName </th>
<th> lastName</th>
</tr>
</thead>
<tbody>
{usersName}
</tbody>
</table>
)
}
}
ReactDOM.render(
<div className="firstContainer">
<Exercice />
</div>,
document.getElementById('root')
)