67

I try get position of click relative to element, but event doesn't have offsetX.

onClick(e) {
  console.log(e.offsetX) // returns undefined
  console.log(e.target.offsetX) // returns undefined
}

render() {
  return <img src='http://placehold.it/1000x500' onClick={this.onClick} />
}

How I can get position of click in element?

Evgeny Rodionov
  • 2,463
  • 2
  • 15
  • 13

2 Answers2

127

Oh, well, I see. I get it from e.nativeEvent.offsetX. Is it right approach?

Evgeny Rodionov
  • 2,463
  • 2
  • 15
  • 13
  • 4
    Yep this is the correct aproach. The event object returned by react is a react SyntheticEvent which wraps the normal JavaScript event object and contains some cross browser conveniences. However, as you found, the native is event can still be accessed on e.nativeEvent. – Mike Driver Jul 20 '15 at 18:17
  • @MikeDriver just do this: `onClick={(e)=>this.onClick(e, e.nativeEvent.offsetX)} ` – Sherali Turdiyev Nov 02 '17 at 20:31
  • 1
    This doesn't work for typescript ```Property 'offsetX' does not exist on type 'Event'.``` – Code Wiget Mar 03 '20 at 15:42
18

I have found that evt.nativeEvent.offsetX was causing me problems with my component flashing a lot and being sort of weird, I haven't fully debugged it, but I switched to using

React.createRef or React.useRef on the parent container, and then using event.clientX - ref.current.getBoundingClientRect().left and found this works better for me

Colin D
  • 2,822
  • 1
  • 31
  • 38
  • 2
    I had the same problem. The event was randomly giving me inconsistent values (`[100, 101, 102, 103, 18, 104, 105]`). This way seems to be more consistent. – Austin Gayler Dec 15 '19 at 19:00
  • 1
    Thanks you for sharing this; saved me a lot of time. – Lucas Wiman Feb 18 '20 at 19:26
  • 2
    Here is a reproduction of the issue I was seeing (fixed by this `getBoundClientRect` approach): https://codesandbox.io/s/delicate-http-nnzx4 Click in the box, then move the mouse back-and-forth. The rectangle between the click and the mouse position will snap to the other side of the screen randomly (tested in Firefox and Chrome on MacOS). – Lucas Wiman Feb 18 '20 at 23:23
  • What if i need to find the position of pointer on that element? – Safwat Fathi May 01 '20 at 19:06
  • 1
    @SafwatFathi the X coordinate of the mouse should be `event.clientX - ref.current.getBoundingClientRect().left` and the Y coordinate should be `event.clientY - ref.current.getBoundingClientRect().top`. If it was a canvas element, you could say ctx.fillRect(x,y,3,3) with those x and y coordinates and it should be accurate for your mouse position over the canvas – Colin D May 01 '20 at 21:35