Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native alignSelf center and stretch to maxWidth?

I have the following

<View style={{maxWidth: 700}}>
  <View style={{backgroundColor: 'red', flexDirection: 'row', justifyContent: 'space-between'}}>
    <Text>Left Item</Text>
    <Text>Right Item</Text>
  </View>
</View>

which is working as I'd expect on a large device (vertical black lines are edges of emulator screen).

enter image description here

All I would like to do is center this on the screen.

When I attempt to do so by adding alignSelf: 'center' to the parent

<View style={{maxWidth: 700, alignSelf: 'center'}}>
  <View style={{backgroundColor: 'red', flexDirection: 'row', justifyContent: 'space-between'}}>
    <Text>Left Item</Text>
    <Text>Right Item</Text>
  </View>
</View>

the width is lost.

enter image description here

I assume this is because by default alignSelf it is 'stretch'. Is there a way to both stretch the content to use maxWidth and center it on the screen?

like image 294
Steven Avatar asked Sep 16 '16 16:09

Steven


People also ask

How do you align items in Center in React Native?

First, go to your android studio and run the emulator. Now start the server again. Example 2: In this example, the entire code will be the same we will just change the value of alignItems property to center and provide the height to the item.


2 Answers

Try using flex:1 along with maxWidth to both make it stretch but limit the width to 700

<View style={{flexDirection:'row', alignItems: 'center', justifyContent: 'center'}}>
    <View style={{flex:1, maxWidth: 700, backgroundColor:'red', flexDirection:'row', justifyContent:'space-between'}}>
        <Text>Left Item</Text>
        <Text>Right Item</Text>
    </View>
</View>
like image 52
FuzzyTree Avatar answered Sep 29 '22 17:09

FuzzyTree


Using maxWidth along with width: '100%' does the trick for me.

like image 27
steventilator Avatar answered Sep 29 '22 17:09

steventilator