Enter Your Email Address to Watch This Lesson

Your link to unlock this lesson will be sent to this email address.

Unlock this lesson and all 833 of the free egghead.io lessons, plus get React content delivered directly to your inbox!



Existing egghead members will not see this. Sign in.

Just one more step!

Check your inbox for an email from us and click link to unlock your lesson.



Get the Dimensions of a React Native Phone Screen

1:10 React lesson by

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.

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

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.

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.



HEY, QUICK QUESTION!
Joel's Head
Why are we asking?