Click delete -> change bg color -> click again to delete

40 Views Asked by At

I am working on a todo list app with react. I have all my todo's listed as list items with the index being the key. Where im at right now is that everything is working, I get a new list item for every item I add, and I can delete the items with a delete button rendered next to the item.

What I want to do is to add a confirmation-step. When I click the delete button I want the background of this item to turn RED, and if I click the delete again I want it to be deleted.

My logic in the delete function is:

<Code>
  const dropItem = (index) => {

    const newItems = [...itemStore];

    newItems.splice([index], 1);

    setItemStore(newItems);

  };
</Code>

How can I change this to add the step I wanted?

If more information is needed just tell me and I will fill in the gaps.

Any help would be greatly appreciated. Cheers.

I have tried to find the solution here on StackOverflow, but only found solutions with alert box or confirmation box.

1

There are 1 best solutions below

1
Mathias Falkenberg On

You will need to manage that as separate states. For instance

const [scheduledForDeletion, setScheduledForDeletion] = useState(-1)

Then add some conditional logic for the delete button handler, e.g:

 const dropItem = (index) => {
   if (scheduledForDeletion === index) {
     // This item is scheduled for deletion, so get rid of it
     const newItems = [...itemStore];

     newItems.splice([index], 1);

     setItemStore(newItems);
     // Remember to reset the scheduledForDeletion state
     setScheduledForDeletion(-1);
   }
   // Actual deletion requires a second pass
   else setScheduledForDeletion(index); 
 };

And use similar logic (comparing the index to scheduledForDeletion) to apply conditional styling