javascriptreactjsonmouseover

React onMouseEnter event for getting X and Y axis of the element


const handleonHover=()=>{
 //get to know the y axis position from the div 
 const rect = event.target.getBoundingClientRect();
 console.log("POS OF Y",rect.y)

}

<div onMouseEnter={()=>handleonHover()}>(height:400px,width:300px) 
<Image>
//image (height:200px,width:100px) 
</Image>
</div>

when mouse enter on the div got y axis (Y Axis - 400), but when hover on the image that placed inside the div got the Y axis from the image is different (Y Axis - 430). how to get the Y axis as per the div (parent) position not image (Child) position?


Solution

  • The onMouseEnter event will return the actual hovered element inside the element you're listening to, or if there's nothing else there, it will return itself. If you want to bypass this issue, you have a short solution using the ref function.

    const ref = useRef(null)
    
      const onHover = (e) => {
        var rect = ref.current.getBoundingClientRect()
        var x = e.clientX - rect.left; 
        var y = e.clientY - rect.top;  
        console.log(x,y);
      }
    
        <div ref={ref} onMouseEnter={onHover}>
            <img src="{your image}" alt="" />
        </div>
    

    Alternatively, you can simply add the CSS property "pointer-events: none;" to the elements inside the parent element. But it is less safe than the first solution.

    Remember to import useRef first

    import { useRef } from 'react';