I am adding table rows to a table dynamically. Here how it looks in the UI:
Here is the logic I am using to create a new row:
I have a state variable this.state = ({rows: []})
on the "Insert" button click I am doing:
addNewRow = () => {
this.setState({rows: this.state.rows.concat([{}])});
}
In my render() I have the below code:
const rows = this.state.rows.map((item, id) => {
return(
<tr key={id}>
<td>Something</td>
<td>Something</td>
<td>Something</td>
<td>Something</td>
<td><Button onClick={(event) => this.removeRow(event, id)}>Delete</Button></td>
</tr>
);
});
and, obviously my final table code looks like the below:
<Table borderless>
<tbody>
{rows}
</tbody>
<tfoot>
<tr>
<td>
<Button onClick={() => {this.addNewRow()}} size="sm" className="float-left">insert</Button>
</td>
</tr>
</tfoot>
</Table>
Here is my removeRow function:
removeRow = (event, id) => {
event.preventDefault();
var index = this.state.rows.indexOf(id);
this.state.rows.splice(index, 1);
this.setState({rows: this.state.rows});
}
The entire code works. I have changed variable names and stripped unwanted codes from them, but this is to give an idea of how I designed it.
My problem is when I click on "Delete" button, it always removes the last item in the row, not the item row which I have clicked. How to fix this?
I googled about the same, and I found few examples, to be honest, I felt they are complex and so I decided to go on my own way.
Please advise what need to be done to fix this issue.
