Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React's mouseEvent doesn't have offsetX/offsetY

Tags:

reactjs

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?

like image 703
Evgeny Rodionov Avatar asked Jul 20 '15 14:07

Evgeny Rodionov


2 Answers

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

like image 176
Evgeny Rodionov Avatar answered Nov 06 '22 07:11

Evgeny Rodionov


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

like image 15
Colin D Avatar answered Nov 06 '22 08:11

Colin D