ReactFix
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • React
  • React Native
  • Programming
  • Object Oriented Programming

Friday, October 28, 2022

[FIXED] where does the position in react-native start from when we use measure inside onLayout?

 October 28, 2022     javascript, react-native, reactjs   

Issue

In react-native when I am trying to get position of a element relative to the screen size. I use measure in OnLayout. What I want to know is if the position pageX that is returned is based on center of the element or from the top of the element.

<View
 onLayout={(event) => {
  event.target.measure((x, y, width, height, pageX, pageY) => {
  console.log(pageX) // Eg. 320
  console.log(pageY) // Eg. 100
 })
}}>
<Text>lorem ipsum</Text>
</View>

Lets say I get the pageX of a circle which is 320.


Is pageX 320 the top of the element?
enter image description here


or is pageX 320 the center of the element?
enter image description here


Solution

PageX indicates the distance of the element to the left of the screen and PageY indicates the distance from the top of the screen. This measurement is made relative to the left and top of the element, not the center.

import { TouchableOpacity, View, } from "react-native"
import React, { useRef } from "react"


export default function Screen() {

    const circleRef = useRef()

    const onPress = () => {
        console.log(circleRef.current.measure(
            (x, y, width, height, pageX, pageY) => {
                console.log({ width, height, pageX, pageY })
                // output: {"height": 100, "pageX": 75, "pageY": 50, "width": 100}
            }))
    }

    return (
        <TouchableOpacity onPress={onPress}>
            <View
                style={{
                    width: 100,
                    height: 100,
                    marginTop: 50, // pageY = 50
                    marginLeft: 75, // pageX = 75
                    borderRadius: 99,
                    backgroundColor: "#000"
                }}
                ref={circleRef}
            />
        </TouchableOpacity>
    )
}



Answered By - SoF
Answer Checked By - - Mildred Charles (ReactFix Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post Home

Featured Post

Is Learning React Difficult?

React is difficult to learn, no ifs and buts. React isn't inherently difficult to learn. It's a framework that's different from ...

Total Pageviews

Copyright © ReactFix