I have this IconButton
which contains AddCircleIcon
:
<IconButton
color="primary"
aria-label="add foo to bar"
name={ bar.name }
onClick={ (e) => {
console.log(e.target.name)
console.log(e.target)
}}
>
<AddCircleIcon
name={ bar.name }
/>
</IconButton>
There's a distinction between clicking on the icon and clicking on the button. Hovering over the icon shows a dim outline around it, the edge of which is the button:
Clicking on the centre of these two, on the plus sign, undefined
is printed on the console. Clicking on the button area outside the icon shows the bar.name
, which is coming from the button.
How would I be able to reference e.target.name
when clicking anywhere on the button, including the icon?
My understanding so far about what's happening is that the onClick
function is run when the icon is clicked upon as well since the icon is contained within the button, however, the event target is the icon. If that's the case, I don't understand why undefined
is printed, as the icon also has name
set.
The second console.log
prints <path d=...
for the icon, does not have a name, no children, appears to be an svg wrapper with nearestViewportElement: <svg ...
along with farthestViewportElement: <svg ...
, parentNode
, parentElement
, ownerSVGElement
, - the both of which have the name
!
Upon looking up how to access the parent for an event on an element, I discovered event.currentTarget
. Using this, I was able to avoid a conditional check on e.target.name
as e.currentTarget.name
prints the name correctly when clicking anywhere on the button, without having to set the name on IconButton
.
Event.currentTarget:
The currentTarget
read-only property of the Event interface identifies the current target for the event, as the event traverses the DOM. It always refers to the element to which the event handler has been attached, as opposed to Event.target, which identifies the element on which the event occurred and which may be its descendant.