Home > Net >  How to disable an onClick event when another OnClick event is also triggered?
How to disable an onClick event when another OnClick event is also triggered?

Time:10-15

Im trying to disable the

<div className="ContainerTitle1" onClick={() => handleAddComponent()}>

when

<div className="accordion1" onClick={(e) => handleExpandItem(e)}>

is clicked becuase it causes both events to happen. How do I create a function to disable the first event from happening when the second happens? thanks. Ill attach a photo for more clarity.

  return (
    <div className="Item1">
      <div className="ContainerTitle1" onClick={() => handleAddComponent()}>
        <div className="buttonTitleWrapper1">
          <p className="Item-Title1">{title}</p>
        </div>
        <div className="ItemIconsContainer1">
          <TypeTag entry={item}></TypeTag>
          {item?.category && <CatagoryTag entry={item}></CatagoryTag>}
          <div
            className="accordion1"
            onClick={(e) => handleExpandItem(e)}
          >
            <img className="arrowIcon" src={AssetExport.BottomIcon}></img>
          </div>
        </div>
      </div>
      <div
        className="panel1"
        style={{
          height: !expanded && "0px",
          overflow: !expanded && "hidden",
        }}
      >
        <p className="desc">{description}</p>
      </div>
    </div>
  );
};

Picture to the code here

CodePudding user response:

Welcome to this community! I'm new too, so I'll try to do my best to answer your question:

What's happening is that when you're clicking

<div className="accordion1" onClick={(e) => handleExpandItem(e)}></div>

You're also clicking

<div className="ContainerTitle1" onClick={() => handleAddComponent()}></div>

Because it is his parent, so both get clicked, but your accordion gets firstly fired since it is the closer one to your screen (capturing phase), then their parents get clicked too (it's like your click event getting propagated to the parents) and their event handlers get fired in consequence.

So, what you are looking for is to prevent the event from propagating from the event target (which is the closest element to your screen) to the parent's event handlers, and you can do so by using event.stopPropagation() inside your handleExpandItem(e) handler, e.g

function handleExpandItem(e){
  e.stopPropagation();
  //Some other stuff you want to do 
}

Here's an article about this issue: https://www.freecodecamp.org/news/event-propagation-event-bubbling-event-catching-beginners-guide/ Hope it helps!

CodePudding user response:

In handleExpandItem add e.stopPropagation(). That way the event will not "bubble up" (propagate) to the parent event handler.

  • Related