I have a simple component like:
<div onClick={toggleHiden} className="faq-item-header">
<h3>What is Bookmark?</h3>
<img src={iconArrow} alt="arrow" />
</div>
This is the onclick function, I just want to toggle classlist.
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?
You need to use event.srcElement instead of event.target, as target is the deepest element you clicked, it may be not the same element you bind the click event with, it can be one of it's children.
Or you can covert you click handler function to a declaration function and use this instead.
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");
}