Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React event bubling / propagation

I have a simple component like:

<div onClick={toggleHiden} className="faq-item-header">
 <h3>What is Bookmark?</h3>
 <img src={iconArrow} alt="arrow" />
</div>

enter image description here

This is the onclick function, I just want to toggle classlist.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const toggleHiden = (e) => {
    console.log(e.target);
    e.target.nextSibling.firstChild.classList.toggle("hidden");
  };

My plan is to run toggleHiden function on div click, but when my mouse click above img or h3 the e.target is changing,
I try to add stopPropagation into the h3:

<h3 onClick={(e) => e.stopPropagation()}>What is Bookmark?</h3>

and now the h3 cannot be clicked.

What I want is whether I click on the img or h3 it still count as click on the parent div

How I can overcome this?

>Solution :

If you are using this approach then you can do following:

if(e.target.tagName === "h3" || e.target.tagName === "img") {             
   e.target.parent.nextSibling.firstChild.classList.toggle("hidden");
}
else {
  e.target.nextSibling.firstChild.classList.toggle("hidden");
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading