React Native - Find View Width and Height

After spending some time with React Native, I came across an instance where I needed the view width of the device I was working on, and it took me a while to find the information. I decided to post a quick way to get the view width and height in React native.


Step 1 - Add a function to the outer view container (either main View or ScrollView). We are using the onLayout function provided by React Native.

 <View onLayout={this.logLayout} >   

Step 2 - Define the logLayout function we used in the above code snippet (this should go in the React class / component, but not in the render method).

 logLayout(event){  
   var width = event.nativeEvent.layout.width;  
   console.log("Width: " + width);  
   console.log(event.nativeEvent.layout);  
 }  

onLayout is called when the view is loaded. "event.nativeEvent.layout" returns an object with the x-axis value, y-axis value, width and height of the container the the onLayout method is called upon. This could also be useful in finding the position of items in the view.

Errors, comments, or questions: email me at dabit3@gmail.com