How to get the coordinates of a touch event with React Native?

Sometimes, we want to get the coordinates of a touch event with React Native.

In this article, we’ll look at how to get the coordinates of a touch event with React Native.

How to get the coordinates of a touch event with React Native?

To get the coordinates of a touch event with React Native, we can get it from the touch event object.

For instance, we write:

import * as React from 'react';
import { TouchableOpacity, Text, View } from 'react-native';
import Constants from 'expo-constants';

export default function App() {
  const onPress = (evt) => {
    console.log(evt.nativeEvent.locationX, evt.nativeEvent.locationY);
  };

  return (
    <View
      style={{
        height: '100%',
        width: '100%',
        justifyContent: 'center',
        alignItems: 'center',
      }}>
      <TouchableOpacity onPress={onPress}>
        <Text>hello world</Text>
      </TouchableOpacity>
    </View>
  );
}

to set the TouchableOpacity‘s onPress prop to onPress.

Then we get the x and y coordinate of the touch from the evt.nativeEvent.locationX and locationY properties.

Conclusion

To get the coordinates of a touch event with React Native, we can get it from the touch event object.