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?
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.
@cody thanks!
:+1: Please close if you're happy with the answer and there is no found bug(s).
You probably want pageX or clientX and if you want it relative to another element you can use getBoundingClientRect on that element – if you do that it should work well across browsers.
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
That seems reasonable enough if we can do it with no performance compromise so I'll reopen this, but it won't be a high priority for us.
I did some work on this and it would require a polyfill. As a property in SyntheticMouseEvent it would execute for every mouse event, which would have a performance impact. It could be added as a method that executed on-demand but then it wouldn't match the native MouseEvent interface.
I’ll close since we decided to not merge #7011.
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

Most helpful comment
offsetX/Yappear to be on the standards track and supported in all major browsers.Any chance of adding them into React - perhaps with a
getBoundingClientRectshim for browsers which don't support it?https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/offsetX