const onMenuItemClick = (event) =>{
console.log("onMenuItemClick data-id",event.target.getAttribute('data-id'));
}
html (JSX) is like this below,
One parent div
which has two children div
<div onClick={onMenuItemClick} data-id="show">
<div className={styles['contextIconBox']}>
<img src={btn_delete} className={styles['contextIcon']}/></div>
<div className={styles['contextLabel']}> myarea</div>
</div>
</div>
When cliking this div onMenuItemClick
is called
However data-id
is not fetched(data-id is null),
I guess maybe, this is becasuse onMenuClick
is fired but event
is not the parent div?
How can I get dhe data-id here?
2
Answers
You’re nested DOM element is retrieving the
onClick
.Use
currentTarget
to get the DOM element from which the current event handler is attached.Or for more complex DOM setups, you might want to add a
className
to eachmenu-item
and then use.closest('.menu-item')
so search for the matching item.You can use
currentTarget
instead oftarget