Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reliable absolute position at screen with React Native

What is the most reliable way to get the absolute position on screen of any element?

I have the problem that when an element above (parent) is added with my methods I can not get the absolute position of an element.

Context: I need to get the absolute position on screen of an element to check if my element which follows the finger (animation made with reanimated) intersects with that element which I can not get the absolute position from.

Methods I have tried:

event.target.measure

Here is the problem that I have a swipe element over the "drop box" and it just produces false positions.

ref.current.measure

This one works but not reliable. It fires about ten times in useEffect and produces only once the correct position.

Are there other things I can try which are reliable? I do not understand why it is so hard to get the absolute position on screen not relative to the parent.

like image 432
Coder949 Avatar asked Dec 01 '21 11:12

Coder949


People also ask

Can I use position absolute in React Native?

position ​ position in React Native is similar to regular CSS, but everything is set to relative by default, so absolute positioning is always relative to the parent. If you want to position a child using specific numbers of logical pixels relative to its parent, set the child to have absolute position.

How do you make a position absolute center in React Native?

To set an item to have position absolute center with React Native, we can set the position to absolute . Then we set justifyContent and alignItems to center to center out item. to set the position , top , left , right and bottom values. Then we center our View by setting justifyContent and alignItems to center .

How do I get a view position on screen in React Native?

To get the position of an element with React Native, we can get it from the View 's onLayout callback. to add a View with the onLayout prop set to a function that gets the position values from the event. nativeEvent. layout property.

Is it good practice to use position absolute?

As long as you structure your HTML so that the elements follow a logical order that makes sense when rendered without CSS, there is no reason why using absolute positioning should be considered bad practice.


1 Answers

I am not sure how your code is connected, and not sure if you want to make this feature in hacky way but you can get the absolute position of the element from on layout property https://reactnative.dev/docs/view#onlayout

like image 138
Dawid Avatar answered Oct 16 '22 21:10

Dawid