Giacomo
Giacomo

Reputation: 43

Adding and removing elements from an array on click in a react application

I have currently this array of objects like this:

const data = [
  {
    name: "jack",
    number: 3,
    isEnabled: false,
  },
  {
    name: "Daniel",
    number: 5,
    isEnabled: false,
  },
  {
    name: "John",
    number: 6,
    isEnabled: false,
  },
];

Inside the render I have mapped the data array to return some divs:

{
  data.map((d) => {
    return (
      <div onClick={() => pushClickedNumbers(d.number)}>
        `${d.name}${d.number}`
      </div>
    );
  });
}

Now I would like to create a function to push that number inside another array state, every time i click on that div, and to remove it when I click again. I've tried something like this to add, but I can't figure it out how to remove it:

const pushClickedNumber = (number) => {
  setArrayOfNumbers(number, ...arrayOfNumbers);
};

The state get populated with the div clicked, but I'm struggling to find a way to remove the same number when I click again on the same div. Thank you

Upvotes: 1

Views: 2140

Answers (1)

Sinan Yaman
Sinan Yaman

Reputation: 5937

First of all, I would change the name of the function since it doesn't only push to the array, but also removes from it based on a condition:

{data.map(d=>{
 return <div onClick={()=>handleNumberClick(d.number)}>`${d.name}${d.number}`</div>
}}

and you can do a simple check inside the function (add if not present, remove if present:

const handleNumberClick =(number)=>{
   setArrayOfNumbers(nums => nums.includes(number) ? nums.filter(n => n !== number) : [number, ...nums])
}

Upvotes: 2

Related Questions