Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React native get the coordinates of my touch event

Tags:

react-native

How would I get the coordinates of my touch event. So I tap anywhere within the display and I can retrieve the X, Y positioning of where it happened.

like image 362
Jonathan Lockley Avatar asked Apr 26 '16 10:04

Jonathan Lockley


People also ask

Why we use TouchableOpacity in React Native?

TouchableOpacity can be used to provide feedback by reducing the opacity of the button, allowing the background to be seen through while the user is pressing down. If you need to handle a tap gesture but you don't want any feedback to be displayed, use TouchableWithoutFeedback.

Which callback is called when a button is tapped in React Native?

Tapping any button will fire the respective onPress callback and dismiss the alert. By default, the only button will be an 'OK' button. This is an API that works both on Android and iOS and can show static alerts.

What is onPress?

Definition of on press : being printed The book is on press now and due out soon.


Video Answer


2 Answers

You will need to wrap your view object with TouchableOpacity or one of the other Touchable components. With TouchableOpacity you have the onPress prop that is passed a press event. From this press event you have access to the x,y coordinates of the press.

pseudo code would look like this:

render() {  ....  <TouchableOpacity onPress={(evt) => this.handlePress(evt) }   .... >   <View></View> </TouchableOpacity> }  handlePress(evt){   console.log(`x coord = ${evt.nativeEvent.locationX}`); } 
like image 65
Hamicorn Fury Avatar answered Sep 19 '22 15:09

Hamicorn Fury


Put it on your view tag and you can get all coordinates

<View onTouchStart={(e) => {console.log('touchMove',e.nativeEvent)}} /> 

For example

<View onTouchStart={(e) => {console.log('touchMove',e.nativeEvent)}} /> 

However this event only work with tag. so you can set view according to your requirement.

like image 33
patel shahrukh Avatar answered Sep 23 '22 15:09

patel shahrukh