How do I preevnt an ion-checkbox from being checked when an icon in its row is clicked?

77 Views Asked by At

I'm using Ionmic 7 with React 18. I have this simple list of items that can be checked or edited.

<IonList>
  <IonLabel>
    <strong>Select Items</strong>
  </IonLabel>

  {items.map((item) => (
    <IonItem key={item}>
      <IonCheckbox
        slot="start"
        name="selectedItems"
        value={item}
      />
      <IonLabel>{item}</IonLabel>
      <IonIcon
        icon={pencilOutline}
        slot="end"
        onClick={onEditHandler(item)}
        style={{ marginLeft: '10px' }}
      />
    </IonItem>
  ))}
</IonList>

The problem is when I click on my "edit" icon (the pencil), the checkbox is being checked and my edit handler is not invoked. The demo is here -- https://stackblitz.com/edit/an5yjh-i9tnnh?file=src%2FApp.tsx,src%2Fcomponents%2FFormWithChceckboxes.tsx. I thought adding this to the handler

e.stopPropagation();

would prevent the checkbox from getting checked and the procedure could continue, but evidently not.

2

There are 2 best solutions below

0
johannchopin On BEST ANSWER

I recommend that you use syntactically correct HTML by using a button to trigger an action

  <IonButton fill="clear" onClick={() => onEditHandler(item)}>
    <IonIcon slot="icon-only" icon={pencilOutline}></IonIcon>
  </IonButton>

Like that you won't need to battle with the bubbling effect.

https://stackblitz.com/edit/an5yjh-b5wpv5?file=src%2Fcomponents%2FFormWithChceckboxes.tsx

0
Unsleeping On

You can resolve the issue by adding a z-index to the edit icon to position it above the IonItem like this:

<IonIcon
  icon={pencilOutline}
  slot="end"
  onClick={onEditHandler(item)}
  style={{ marginLeft: '10px', zIndex:10 }}
/>