I have a wrapper that has an on-click but I want that to work only if it clicked within a specific child div or more exactly the first div, but I don't know how to do that.
Here for example:
<div onClick={() => openMenu()}> // this opens and closes menu
<div>
Menu
</div>
<div> // this is hidden then later when openMenu&&true it shows
Menu Dropdown and its content
</div>
<div>
So what I want to do is when I click the first child Menu Item to call the function but when the second child is clicked it will not called.
CodePudding user response:
Set the div element on data-id. And looking for this attr in the event. For example:
const handleNormalMenu = (e) => {
console.log(e.target.dataset.id)
}
<div data-id={id} onClick={handleNormalMenu}></div>
CodePudding user response:
I made the codepen for you.
https://codepen.io/endmaster0809/pen/mdBmeXq
Simply, there is a dom function called contains
, you can check it in your onClick handler like I did.
if (container !== event.target && !container.contains(event.target)) {
// this is outside
} else {
// this is inside
}
For full code, you can check my codepen.