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.
Duration
1 min
Access
Free
Transcript
Available
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.
Video Transcript
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.