This Lesson is for Members

Subscribe today and get access to all lessons! Plus direct HD download for offline use, enhances transcripts, member comment forums, and iTunes "podcast" RSS feed. Level up your skills now!

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    Measure and Get the Position of a React Native Element

    Jason BrownJason Brown

    In this lesson we'll explore how to measure the dimensions and get the position of a React Native element using onLayout and UIManager.measure. Additionally we'll see how to use the helper function measure on the component ref for easier measurement.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    00:00 We'll start by putting UIManager and findNodeHandle from react-native. Let's take a quick look at our application. We have a View that we want to measure. We have a button to trigger our measure, and we have some output on the screen of the View measurements that we take.

    00:15 The first method of measuring a View is using the property onLayout. It's a function that passes in an event with a nativeEvent, we'll de-structure that. We then call this.setState. We'll set our measurement to nativeEvent.layout.

    00:35 NativeEvent.layout will contain Width, Height, X, and Y. This function will be called each time the layout is rendered. If we refresh, we can now see that our measurements are coming through.

    00:47 Now, we'll add a ref to our View that we want to measure. We say "ref," we give a callback ref, and sign this.view = ref. Now, we'll give our TouchableOpacity the onPress property. Then, call a function called this.measure.

    01:02 We go create the measure function. Then, we'll use UIManager which has a measure function, which takes a node handle. We'll need findNodeHandle. I'll pass in our ref, this.view. Then, it synchronously measures the View. We'll then pass in a callback and say this.setState, measurements, which is our object.

    01:33 Each argument is passed in separately. Our X, our Y, our Width, and our Height. We'll put that here, X, Y, Width, and Height. When I save this and refresh and then tap here, you can see that our X changed just a little bit.

    01:55 If we don't want to import UIManager, you can also use the help method on the reference. We say this.view.measure. We no longer need our NodeHandle.

    02:07 We'll then pass in our callback. If we refresh, and you can see that we also then had our x changed a little bit...

    Discuss

    Discuss