Wolfdog
Wolfdog

Reputation: 587

React Native Flex Height

So I am learning React Native Flex, and came across this problem:

Let's focus only on Body and it's content.

<View style={styles.body}>
  <View style={styles.container}>
    <View style={styles.yellow}></View>
    <View style={styles.orange}></View>
  </View>
</View>

body: {
  flex: 15,
  justifyContent: 'center',
  alignContent: 'center',
}

Inside Body, I want to have this kinda-like container which will hold elements inside it.

1) If I give flex < 1, I get it shrinked only by height.

container: {
   flex: 0.9,
   flexDirection: 'row',
}

enter image description here

2) If I give width and height, only width works.

container: {
   flex: 1,
   flexDirection: 'row',
   width: '90%',
   height: '90%', // doesn't work?
   alignSelf: 'center' // had to add this, without it, container would stick to left side
}

enter image description here

3) Adding margin as percent, sticks the whole container to bottom, and alignSelf doesn't work.

4) Adding margin as number, works, but I want to avoid pure numbers since they look different on other devices. (Also, this is desired)

enter image description here

How do I achieve effect from last picture, but only with flex and width,height in %? Is it even possible?

Also, what is good practice for cases like this?

Upvotes: 4

Views: 12952

Answers (1)

sebastianf182
sebastianf182

Reputation: 9978

So this is how you do it using only flex:

 <View style={{flex: 1}}>

            <View style={{flex: 0.1, backgroundColor: 'red'}}/>

            <View style={{flex: 1, borderColor: 'green', borderWidth: 15}}>

            <View style={{flexDirection: 'row', flex: 1}}>
                <View style={{flex: 0.4, backgroundColor: 'yellow'}}/>    
                <View style={{flex: 0.6, backgroundColor: 'orange'}}/>   
            </View>

            </View>

            <View style={{flex: 0.1, backgroundColor: 'red'}}/>

            </View>

Some explanation. Flex is relative and is used from 0 to 1. Making 1 tells RN to use all available space. Making 0.1 is telling TN to use "up to 10% of all available space". That is what I used for the header and footer. Of course you might want to use another value.

For the middle block flex is 1, because I want that to fill everything else. Then the border is there to show the green but you can also use padding or margin. Should not make a difference.

Lastly, if you want to stack layouts horizontally, you need to use flexDirection: 'row' (Default is column). Then the children have 0.4 and 0.6 flex, which tells RN to use 40% and 60% of all available horizontal space. This is the same as using width.

Results:

Layout

Let me know if this is not what you want. Cheers

Upvotes: 8

Related Questions