React Native Get Screen Coordinates Dynamically iOS Android Tutorial

Hi guys today, I am going to explain and show you how we can get screen coordinates dynamically in react native. I have done this task using PanResponder  react native inbuilt API and I want to share this interesting aspect with all of you guys through this tutorial.

In brief, what will we do in Get Screen Coordinates Dynamically tutorial?

  • I am using PanResponder  react native inbuilt API to perform this task.
  • I am using a small size View  with red background and update the position( X, Y ) of this View when user clicks anywhere on the screen.
  • And I am also using a Text  component on the top of the screen to show the current clicked coordinates.

Let’s begin…

Step – 1: Import all required components from react , react-native .

Step – 2: Implement constructor  method.

Explanation:

  • locationX , locationY  state variables will get updated when new screen coordinates will be calculated and with the help of these state variables the position of red background View will be updated.

Step – 2: Implement componentWillMount  method.

Explanation:

  • As you can see in the above code that react native PanResponder  API provides many handlers like onStartShouldSetPanResponder , onPanResponderMove  etc. In our case, we have to implement onPanResponderMove  method. Using event  parameter of onPanResponder  handler we can get the X and Y position of user clicked area on the screen.

Step – 3: Implement render  method.

Step – 4: Implement styles of all required components.

Complete Source Code:

Step – 5: Execute react-native run-ios  to run app in iOS devices and / or execute react-native run-android  to run app in Android devices.

  • iOS Screenshot:

 

  • Android Screenshot:

Guys enjoy and have fun…

Leave a Reply

Your email address will not be published. Required fields are marked *