Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Get the Dimensions of a React Native Phone Screen

    react-nativeReact Native

    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.



    Become a Member to view code

    You must be a Pro 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
    orLog In




    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.

    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().

    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.