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 ?
you can use event.currentTarget.id
. In case you wondering whether to use currentTarget
or target
, 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.
function App(){
const handleHover = (event) => {
const { id } = event.currentTarget
console.log(event.currentTarget)
console.log(event.target)
console.log(id)
}
return (
<div className="part-3" id="graph-1" onMouseEnter={handleHover}>
<h3 className="chartHeader">Avg. marks per subject </h3>
<span>Something</span>
</div>
);
};
ReactDOM.render(<App />, document.getElementById("app"));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="app"></div>