React's mouseEvent doesn't have offsetX/offsetY

Reactjs

Reactjs Problem Overview


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?

Reactjs Solutions


Solution 1 - Reactjs

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

Solution 2 - Reactjs

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEvgeny RodionovView Question on Stackoverflow
Solution 1 - ReactjsEvgeny RodionovView Answer on Stackoverflow
Solution 2 - ReactjsColin DView Answer on Stackoverflow