Search code examples
react-nativeflexboxreact-native-flexbox

How to vertically stretch two Views that are in a column formation - React Native Flex?


I have this view, where there are two Views in a column:

    <View style={styles.container}>
        <View style={styles.content}>
            <View style={{backgroundColor: 'orange'}}>
                <Text>Test</Text>
            </View>
            <View style={{backgroundColor: 'yellow'}}>
                <Text>Test2</Text>
            </View>
        </View>
    </View>

This is my Styles:

container: {
    flexDirection: 'row',
    backgroundColor: 'white',
    justifyContent:'center',
    alignItems:'center',
    height: 80,
    margin: 8,
},
content: {
    flex:1,
    alignItems: 'stretch',
    flexDirection: 'column',
},

Here is a ScreenShot of what it looks with the above code.

How can I get the orange and yellow View to expand vertically equally, without manually defining the height for each of them?

The Text inside should be centered, but left-aligned.


Solution

  • Add flex: 1 to each cell to make them expand and add justifyContent: 'center' to make the text vertically centered. Like this:

      <View style={styles.container}>
        <View style={styles.content}>
          <View style={{ backgroundColor: 'orange', flex: 1, justifyContent: 'center' }}>
            <Text>Test</Text>
          </View>
          <View style={{ backgroundColor: 'yellow', flex: 1, justifyContent: 'center' }}>
            <Text>Test2</Text>
          </View>
        </View>
      </View>