I wrote the below code to capture the id
for the div, when the user hovers
over the div.
<div className="part-3" id="graph-1" onMouseEnter={handleHover}>
<h3 className="chartHeader">Avg. marks per subject </h3>
{<MarksDisplayTable/>}
</div>
My handleHover
function looks as below –
const handleHover = (event) => {
console.dir("event = " + Object.keys(event));
}
I was expecting that the target
key will contain id
for the div. But, it only consists of 2 private keys.
Output –
event = __reactFiber$593cb2h2ba,__reactProps$593cb2h2ba
How can I capture the id = graph-1
using onMouseEnter
action ?
2
Answers
you can use
event.currentTarget.id
. In case you wondering whether to usecurrentTarget
ortarget
, the current target will catch the parent<div>
regardless you hover over its children. Target will catch the children if you hover over the children.To capture the
id
of adiv
when the user hovers over it using theonMouseEnter
event in React, you can access thetarget
property of the event object. Thetarget
property will give you the DOM element that triggered the event, and from there you can access its attributes, includingid
.Here is how you can get the
id
.In this scenario, you could have used
event.target
instead ofevent.currentTarget
. However, to reliably capture theid
when the user hovers over thediv
, you should useevent.currentTarget
becauseevent.currentTarget
always refers to the element to which the event handler is attached.In your case, it consistently refers to the
div
element with theonMouseEnter
event listener, whereasevent.target
refers to the element that actually triggered the event. If the user hovers over a child element inside the div (like an<h3>
element),event.target
would point to that specific child element.