Get the Dimensions of a React Native Phone Screen

Jason Brown
InstructorJason Brown
Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 5 years ago

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.

[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.

egghead
egghead
~ 11 seconds ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today