1

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

2
  • So, you want to add the number and remove the number in the same onClick function? Commented Sep 9, 2021 at 14:26
  • Provide a reproducible example Commented Sep 9, 2021 at 14:26

1 Answer 1

2

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])
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.