5

I want to determine the position of my element from top of the screen. From other questions, one way to do is by using .measure property of react native?

Ref Question: React Native: Getting the position of an element

So I did something like this

const AutoComplete = (props) => {
  let parentViewRef =  useRef(null);
  return (
       <View 
        style={styles.modelOpenViewMain}>
        <View  ref={parentViewRef} 
        onLayout={({nativeEvent}) => {
          console.log(nativeEvent)
          if (parentViewRef) {
            parentViewRef.measure((x, y, width, height, pageX, pageY) => {
                      console.log(x, y, width, height, pageX, pageY);
             })
            }}}/>
        <View style={styles.modelOpenInputView}>
          <TextInput
              value={value.label}
              onChangeText={(text) => onchangeHandler(text)}
              style={[{color: defaultColor, borderColor: defaultColor}, styles.defaultTextInputStyle, textInputStyle]}
            />
          </View>
      </View>
)
}

console for my parentViewRef is giving me this console.log(parentViewRef)

_nativeTag: 73
_children: []
viewConfig:
uiViewClassName: "RCTView"
Commands: {}
bubblingEventTypes: {topSelect: {…}, topBlur: {…}, topChange: {…}, topEndEditing: {…}, topFocus: {…}, …}
directEventTypes: {topClick: {…}, topContentSizeChange: {…}, topLoadingError: {…}, topLoadingFinish: {…}, topLoadingStart: {…}, …}
validAttributes: {hasTVPreferredFocus: true, focusable: true, nativeBackgroundAndroid: true, nativeForeg 

And there isn't any function measure in there, Can someone help me in figuring out what I am doing wrong?

Just in case: I am logging my parentViewRef after 3 seconds

setTimeout(() => {
  console.log(parentViewRef)
 }, 3000);
Alwaysblue
  • 9,948
  • 38
  • 121
  • 210

2 Answers2

0

Since you are assigning onLayout prop already, you can have y from there

onLayout={({ nativeEvent }) => console.log(nativeEvent.layout.y)}

.measure (if you still need it, but I imagine you don't) should be called at some point later in time in respond to some event, but after onLayout was executed at least once

Max
  • 4,473
  • 1
  • 16
  • 18
0

When using a ref, you need to access the referenced object using parentViewRef.current. In your case parentViewRef.current.measure.

I have the same issue with measure being undefined, so I'm not sure if that solves your problem, unfortunately it didn't solve mine

K.N.
  • 1
  • 1