-1
I wrote the following code below, it is 100% functional with one exception.
By clicking "remove" on the desired line, it removes the last line, not the correct one (that is, add 5 lines, ask q to remove the second, and actually remove the last).
Curious that in the array it removes correctly, the problem is only in the view.
The code is very simple and functional, copying and compiling anywhere should work well.
Can you help me with this last missing item (referring to removing the correct line - preferably using typescript)? Thank you.
import React, { useState } from 'react';
export default function Test() {
const [infos, setInfos] = useState([
{ 'info1': '', 'info2': '', 'info3': '' }
]);
function addNewInfoItem() {
setInfos([
...infos,
{ 'info1': '', 'info2': '', 'info3': '' }
]);
};
function removeInfoItem(index: any) {
const itensCopy = Array.from(infos);
itensCopy.splice(index, 1);
setInfos(itensCopy);
};
function updateInfosItem(position:number, field:string, item:string) {
const updatedInfoItems = infos.map((standardItem, index) => {
if (index === position) {
return { ...standardItem, [field]: item }
}
return standardItem
})
setInfos(updatedInfoItems)
}
return (
<div>
{infos.map((item, index) => {
return (
<div key={index}>
<button onClick={e => removeInfoItem(index)}> Remover </button>
<input
required
type="text"
onChange={e => updateInfosItem(index, 'info1', e.target.value)}
/>
<input
required
type="text"
onChange={e => updateInfosItem(index, 'info2', e.target.value)}
/>
<input
required
type="text"
onChange={e => updateInfosItem(index, 'info3', e.target.value)}
/>
</div>
);
})}
<pre> {JSON.stringify(infos, null, 4)} </pre>
<button onClick={addNewInfoItem}> Adicionar </button>
</div>
);
}