7

I'm trying to get the position of a component in react native.

Say I have a view:

<ScrollView>
    lots of items...
    lots of items...
    lots of items...
    <View></View>
</ScrollView>

In the end I want to be able to eventually scroll to where the View is.

This link shows how to get the position using the native ui manager, however when ran it returns:

"Attempted to measure layout but offset or dimensions were NaN"

React Native: Getting the position of an element

I've attempted

this.refs.VIEW.measure((ox, oy, width, height, px, py) => {
    //ox ... py all = 0
});
David Schumann
  • 13,380
  • 9
  • 75
  • 96
Lfa
  • 1,069
  • 2
  • 10
  • 23

2 Answers2

13

You might want to use the onLayout callback on the View component. setTimeout may not work 100% of the time.

<View onLayout={this.measureMyComponent} />
David Schumann
  • 13,380
  • 9
  • 75
  • 96
zero
  • 989
  • 11
  • 18
  • It does not help for me. I still get 0 for x and y. Any other ideas? – Dmitry Feb 15 '17 at 17:16
  • It appears to get the co-ordinates relative to the thing that contains it. So if it is at `{ left: 0, top: 0 }` relative to the View that contains it, then x and y will both be 0. – Wodin Feb 20 '20 at 13:58
11

Sometimes if you're using measure in componentDidMount you have to wrap it in a setTimeout:

setTimeout(() => {
    this.refs.VIEW.measure((ox, oy, width, height, px, py) => {
    });
}, 0);
David Schumann
  • 13,380
  • 9
  • 75
  • 96
Colin Ramsay
  • 16,086
  • 9
  • 52
  • 57
  • This must mean the components are being loaded asynch and not really fully loaded when component did mount was called. setTimeout throws the function onto the event loop eventually making it processed after the components are fully layed out? – Lfa Jul 25 '15 at 17:10
  • `this.refs` is no longer valid... I tried the following https://snack.expo.io/ryywtvoTb without luck – Norfeldt Oct 23 '17 at 13:09