I would like to remove an item from array onClick by using the prevState syntax.
Here is an example code that i use:
export default function App() {
const [selected, setSelected] = useState(false);
const [selectedItems, setSelectedItems] = useState([]);
const [cards, setCards] = useState(["card1", "card2", "card3", "card4"]);
function handleButtonClick(event) {
setSelected(true);
let key = event.target.id;
key = parseInt(key, 10);
if (selectedItems.indexOf(key) === -1) {
setSelectedItems([...selectedItems, key]);
} else {
// HOW do i remove the item from the array ????
let index = selectedItems.indexOf(key);
}
}
return (
<div className="App">
{cards.map((card, index) => (
<button
className={
selected && selectedItems.indexOf(index) !== -1
? "button1 active"
: "button1"
}
onClick={handleButtonClick}
id={index}
>
{card}
</button>
))}
</div>
);
}
link to sandbox as well : https://codesandbox.io/s/patient-thunder-mb1vx?file=/src/App.js