Evgeny Rodionov
Evgeny Rodionov

Reputation: 2633

React's 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?

Upvotes: 71

Views: 38088

Answers (3)

React not supporting offsetX/offsetY on MouseEvent is a limitation of React tracked here: https://github.com/facebook/react/issues/4431

The PR to add the support was closed in 2016 since back then supporting all browsers turned out to be too much for the React team to want to include the support.

In 2024, the level of support for offsetX/offsetY is baseline-level:

React not supporting this today is an API choice and hopefully one they reverse.

Upvotes: 1

Colin D
Colin D

Reputation: 3111

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

Upvotes: 19

Evgeny Rodionov
Evgeny Rodionov

Reputation: 2633

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

Upvotes: 139

Related Questions