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
});
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.
To get the coordinates of a touch event with React Native, we can get it from the touch event object. to set the TouchableOpacity 's onPress prop to onPress . Then we get the x and y coordinate of the touch from the evt. nativeEvent.
Creating RefsRefs are created using React.createRef() and attached to React elements via the ref attribute. Refs are commonly assigned to an instance property when a component is constructed so they can be referenced throughout the component.
You might want to use the onLayout callback on the View component. setTimeout may not work 100% of the time.
<View onLayout={this.measureMyComponent} />
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);
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