I try to make a table and to create row on each click on button, to do that, I made 2 useStates -
const [rowsInTable, setRowsInTable] = useState([0]);
const [addedRows, setAddedRows] = useState([]);
this is the function that runs on button click -
const addRowFunc = (e, newRow) => {
e.preventDefault();
const add = setRowsInTable([...rowsInTable, newRow]);
rowsInTable.map((row, index) => {
return setAddedRows([
...addedRows,
<tr key={index}>
<td>
<input type="file" />
</td>
<td>
<input type="text" />
</td>
<td>
<input type="text" />
</td>
<td>
<input type="text" />
</td>
<td>
<input type="text" />
</td>
<td>
<TextareaAutosize minRows={2} />
</td>
<td>
<input type="date" name="" id="" />
</td>
<td>
<input type="date" name="" id="" />
</td>
<button key={index} onClick={(e) => deleteRow(e, index)} className="deleteButton">X</button>
</tr>,
]);
});
};
and as you can see it renders a button for each that run another function on click that removes the table row..
this it the function:
const deleteRow = (e, index) => {
e.preventDefault();
const rowsNum = [rowsInTable]
const rowsElements = [addedRows]
rowsNum.splice(index, 1)
rowsElements.splice(index, 1)
setRowsInTable(...rowsNum)
setAddedRows(...rowsElements)
}
so 2 things.. the first one is that when i try to delete a row the row with the index I click on get deleted but it also delete the all next in the array.. if i click index-5 and i have 10, 5-10 gets deleted..
second thing is, I want the state to start clean or overwrite the 0 in the array after first interaction.. can't come up with a solution for that, so i'll appreciate one..
thanks! :)