CodeBy
CodeBy

Reputation: 762

React Native - how set View size screen size independently?

I'd like make View will be looked the same at different sizes (for Android 4+) and dpi (240+), as well IPhone 4+ and IPad. When I define size, ex. 270x65, it looks double size in screen with 640 dpi than same size in screen 320 dpi (2560x1600 real screen size).

Is this a good solution?

  containerButton: {
    width: calcDimension(270),
    height: calcDimension(65)
  }

const calcDimension = size =>
  size / (screenScale() > 2 ? (screenScale() / 2) : 1);

const screenScale = () =>
  (Dimensions.get('window').scale);

Or there could be better solution? Thank you.

Upvotes: 0

Views: 9839

Answers (3)

A.R.Basith
A.R.Basith

Reputation: 181

you can use vw or vh to set the dimensions.

for example: height:"90vh", width:"50vw" will set height of the respective element 90% to the window size and width 50%.

Hope this helped.

Upvotes: 0

Satish Sojitra
Satish Sojitra

Reputation: 632

You can use Dimensions in react native to get device height and width calculated automatically.

First import Dimensions

import { Dimensions, Platform, StyleSheet } from 'react-native

Get device height and width

var deviceHeight = Dimensions.get('window').height;
var deviceWidth = Dimensions.get('window').width;

Now you can use this global variable in your styles. for example:

const styles = StylSheet.create({
     mainContainer: {
          height: deviceHeight/2;
          width: deviceWidth/2;
     }
});

You can also dynamically calculate statusbar height and width standard way:

var STATUS_BAR_HEIGHT = Platform.OS === 'ios' ? 20 : 25;
var HEADER_HEIGHT = Platform.OS === 'ios' ? 44 + STATUS_BAR_HEIGHT : 44 + STATUS_BAR_HEIGHT;

Upvotes: 6

Codesingh
Codesingh

Reputation: 3384

I have just gone through your query and i think it would be great if you try using "dimensions" . Dimensions is another important parameter which is provided by react native it self. What you need to do is just import the dimension in your component.

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

The above command will set height and width of the device according no matter it is iphone or android.

Just go throung the link: https://facebook.github.io/react-native/docs/dimensions.html

Cheers :)

Upvotes: 2

Related Questions