Here is my component which will be mapped and rendered several times in the app. When you clicks on it, its title will be added to an array list and if it was already added to the list it will be removed from the array list (toggle):
export default function Card({ title, info, id, list, setList }) {
return (
<div className="bg">
<h1 className="color">{id}</h1>
<h2 className="color">{title}</h2>
<p className="color">{info}</p>
<button
onClick={() => {
if (list.includes(title)) {
setList(list.filter((el) => el !== title));
} else setList([...list, title]);
}}
>
click to add
</button>
</div>
);
}
The way I achieved this was by using the filter and {[...list], title}. I was told not to modify the array directly and I have no idea why. Push and pop methods could have easily handled this logic. What makes them ineffective?