react: mouseEvent doesn't have offsetX/offsetY

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?

About this issue

  • Original URL
  • State: closed
  • Created 9 years ago
  • Comments: 15 (5 by maintainers)

Most upvoted comments

As of 2020, this doesn’t seem to need a polyfill. But SyntheticEvent’s MouseEvent doesn’t have offsetX or offsetY

I can submit a PR if you want

https://caniuse.com/#feat=mdn-api_mouseevent_offsetx

image

offsetX/Y appear to be on the standards track and supported in all major browsers.

Any chance of adding them into React - perhaps with a getBoundingClientRect shim for browsers which don’t support it?

https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/offsetX

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

This shows all available values:

onClick(event) {
  event.persist();
  console.log(event);
}

Using the nativeEvent is fine.

Why the Facebook developers add them into e.nativeEvent?

@amerllica e.nativeEvent is created by the browser, so if there is e.nativeEvent.offsetX the browser supports it. Why the attribute does not propagate to synthetic event, that is question to React team.

@gaearon, Why ReactJs mouseEvent doesn’t have which, offsetX, offsetY and etc?

Why the Facebook developers add them into e.nativeEvent?