Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle responsive layout in React Native

I'm using the react-native-dimension library for making my UI responsive as follows:

const{width,height} = Dimensions.get('window');

and in my style.js file :

imageBackgroundLandscape:{
    width:height,
    height:width

},
imageBackgroundPortrait:{
    width:width,
    height:height
}

The problem is that when I rotate the screen, the width and height variables have got previous values! For example in the portrait mode my variables are:

width : 800
height: 1280

and when I rotate the screen my variables are:

width : 800 // previous value
height: 1280 // previous value

In addition, I use the react-native-orientation to determine the mode of the screen. I want to know how can I change the values of them (width, height) automatically when I rotate the device, or are there any other libraries for this?

Thanks in advance.

like image 542
alirezafc Avatar asked Oct 22 '25 08:10

alirezafc


1 Answers

I usually handle the height, width confusion with the following code:

//Dimensions.js
import {Dimensions} from 'react-native';
const {height, width} = Dimensions.get('window');

const actualDimensions =  {
  height:  (height<width) ? width : height,
  width: (width>height) ? height : width
};

export default actualDimensions;

Instead of requiring the height and width from Dimensions, use the actualDimensions and for managing the orientation gracefully you should give a try to this library as well.

The Dimensions are loaded before the JS bundle gets loaded into the app so it is recommended to fetch the height, width dynamically for every render You can read this here

like image 131
Suraj Malviya Avatar answered Oct 24 '25 08:10

Suraj Malviya