Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define width by percentage in react native?

I am trying to create a view with a border around it that is centered and fills 80% of the screen. I have come up with this:

<View style={{flexDirection: 'row'}}>
  <View style={{flex: .1}} />
  <View style={{flex: .8, borderWidth: 2}} />
  <View style={{flex: .1}} />
</View>

which works, but seems awfully verbose.

Is there a better (more succinct) way to create a view that is a certain percentage of the screen width and centered in the page?

like image 584
Abe Miessler Avatar asked Jul 23 '16 21:07

Abe Miessler


People also ask

How is screen width calculated in React Native?

You can get the application window's width and height using the following code: const windowWidth = Dimensions. get('window').

Can we give margin in percentage in React Native?

minWidth ​ minWidth is the minimum width for this component, in logical pixels. It works similarly to min-width in CSS, but in React Native you must use points or percentages. Ems and other units are not supported.

How do you set dynamic height and width in React Native?

In react-native, to set the dynamic width and height to a component, we use built-in interface Dimensions. it takes the dimension of a given component and then sets the width and height to its equivalent.


Video Answer


1 Answers

UPDATE:

Starting from React Native version 0.42 we now have a full percentage support for width, height , padding and so on, see the full list and examples here: https://github.com/facebook/react-native/commit/3f49e743bea730907066677c7cbfbb1260677d11

Old method:

Consider using Dimensions, like:

import Dimensions from 'Dimensions';

and then in element's style:

width: Dimensions.get('window').width / 100 * 80,

Working example: https://rnplay.org/apps/4pdwlg

like image 71
Ivan Chernykh Avatar answered Oct 08 '22 08:10

Ivan Chernykh