I'm trying to remove an item from an error but it's not working like expected.
Im using state:
const [actions, setActions] = useState([
{
action: "",
key: ""
}
]);
I have a button to add actions:
<IconButton
icon="add"
bgColor="white"
iconColor="darkGray"
onClick={() =>
setActions([
...actions,
{
action: "",
key: ""
}
])
}
/>
Each row has a delete and I'm trying to use the row index to delete the item in the actions array:
<IconButton
disabled={actions.length === 1}
icon="dash"
iconColor="red"
onClick={() => {
console.log(index);
setActions(actions => {
return [...actions.splice(index, 1)];
});
}}
/>
Try using filter
. It does not modify the existing array and can be used like this:
setActions(prevActions => (
// Filter out the item with the matching index
prevActions.filter((value, i) => i !== index)
));
<IconButton
disabled={actions.length === 1}
icon="dash"
iconColor="red"
onClick={() => {
setActions(actions.filter((item, i) => i !== index));
}}
/>
I tested it in your Codesandbox and it worked
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.