Steven Steven - 2 months ago 18
React JSX Question

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?

Answer

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>
Comments