I have a problem. When i select and delete some of array object added on usestate. it’s not deleting the selected. i don’t know why. the slice method is working fine when i console log it. the selected index is correct. but when i update the usestate array object the selected index is not working. the only working is the last index deleted.
here is the some of example. i selected and remove the orange
but it’s not removing the last item guava
was removed not the orange i select.
Here is usestate benefits array object :
const [benefits, setBenefits] = useState([{name:''}])
Here is my onChange handlerDescription
const handlerDescription = (index,e) =>{
e.preventDefault();
let temp = [...benefits]
temp[index] = e.target.value
setBenefits(temp)
//all value will store here
}
Here is my onClick handlerCloseRow
const handlerCloseRow = (index) => {
const newItems = [...benefits]; // create a copy of the array
newItems.splice(index, 1); // remove the item at the specified index
setBenefits(newItems); // update the state with the updated array
};
Here is my onClick handlerAddRow
const handlerAddRow = (e) =>{
e.preventDefault();
setBenefits([...benefits,{
name:''
}])
}
Here is my code. the handlerAddrow is not inside on MAP method
<section>
<label>
Description
</label>
{benefits.map((benefit,index)=>(
<div key={index} className="mb-4">
<Input onChange={(e)=>handlerDescription(index,e)} value={benefits?.name} type="text" />
<button onClick={(e)=>handlerCloseRow(index,benefit,e)}>close</button>
</div>
))}
<div onClick={handlerAddRow}>
<button className="text-3xl"/><span>Add Row</span>
</div>
</section>
2
Answers
Since you want to save a
benefit
as an object, you may modify thehandlerDescription
like this.Also, in the map operation, each input value should be
benefit.name
instead ofbenefits?.name
.Hope it may help.
When you want to remove one element from the state’s array you can create a temporary array with the new array:
You can test it on this example I prepared: https://stackblitz.com/edit/react-ts-qjhr8l?file=App.tsx