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.
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.
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 .
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With