Home > Software design >  How to get the actual X Y coordinates of pointer on element in react
How to get the actual X Y coordinates of pointer on element in react

Time:10-20

I'm using onPointer events in react.js I can get the actual XY coordinates with event.pageX and event.pageY values or client and screen. but when I'm setting margins, paddings or moving the element to another positions, my coordinates are still from XY values of the whole screen size. How can I reference my element? I know that useRef() is there, but how can I reference it without subtracting paddings or margins, I want them to be relative referenced because I will use them a lot in my app. What's your solution?

const App = () => {
  const [coordinates, setCoordinates] = useState([]);

  return <div
    style={{margin: "30px"}}
    onPointerDown=
      {(event) => setCoordinates([...coordinates, `{event.clientX} {event.clientY}`]}
    id="elementiwanttoref">{coordinates.map((cord) => <span>{cord}</span>)}</div>
}

CodePudding user response:

const App = () => {
    const inputRef = useRef(null);

    useEffect(() => {
      console.log(inputRef.current.offsetLeft);
      console.log(inputRef.current.offsetTop);
    }, []);

    <Component ref={inputRef} />
}

CodePudding user response:

If I understand correctly, you are looking for a coordinates relatively to element. With offsetX and offsetY properties we can get this, but it will be relatively to event listener's target element(we cannot re-calculate dynamically for some random another element).

  • Related