'Getting coordinates of a touch in React Native (Expo)
I need to get (relative) coordinates of a click/touch in React Native.
I tried using RN <View onPress={(e: GestureResponderEvent) => ...}>
On the Web, I further use e.nativeEvent which is of the type PointerEvent, and I use layerX, layerY which give me exactly numbers I need.
Unfortunately, the iOS native event has similar fields named locationX and locationY.
I have to use this ugly code to get the coordinates
interface IEvent {
layerX?: number
layerY?: number
locationX?: number
locationY?: number
}
const { layerX, layerY, locationX, locationY } =
e.nativeEvent as unknown as IEvent
const x = layerX ?? locationX
const y = layerY ?? locationY
Is there a better cross-platform way of doing it? Perhaps I need to use another control or another event?
Solution 1:[1]
Just in case someone needs it.
I changed the event to onPressIn(e). e.nativeEvent events consistently using locationX and locationY across the Web and iOS.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | GRZa |
