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

    Get the Dimensions of a React Native Phone Screen

    Jason BrownJason Brown

    In this lesson we'll use Dimensions to get the width and height of the screen. Also we'll use onLayout to detect orientation changes.

    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 importing Dimensions from React Native. Next, we'll make a call to Dimensions.get, which is a function that takes an argument of 'window', then returns an object of width and height. We'll say, const{width, height}, and destructure at the width and height, and then set them on our state.

    00:20 If we look at our application, we can see that we're rendering width and height on the screen, and that we have the Dimensions at the time that the application is run. When I refresh, we get the width and height of our application. To detect an orientation change, we can add an onLayout property to our outer view which is a function, and then we'll call, this.onLayout().

    00:45 Now, we'll create our onLayout function, then we'll take our Dimensions call and we'll put it on our onLayout function. We'll then call, this.setState() and our width and our height just like we did before, refresh. We still have our simple width and height. Now, if I rotate left, you can see that the width and the height changed, and then when I rotate back, you can see that they change back again.

    Discuss

    Discuss