Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native - Get the position of a component in the View

Tags:

react-native

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
});
like image 417
Lfa Avatar asked Jul 24 '15 18:07

Lfa


People also ask

How do you get the position of a component on screen in React Native?

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.

How do you get touch position in React Native?

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.

How do you ref a component?

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.


2 Answers

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

<View onLayout={this.measureMyComponent} />
like image 52
zero Avatar answered Oct 07 '22 01:10

zero


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);
like image 39
Colin Ramsay Avatar answered Oct 07 '22 00:10

Colin Ramsay