Abe Miessler
Abe Miessler

Reputation: 85086

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?

Upvotes: 6

Views: 2870

Answers (1)

Ivan Chernykh
Ivan Chernykh

Reputation: 42176

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

Upvotes: 6

Related Questions