What is the exact purpose of setting rule flex: 1
to many React Native components?
Very often I can see this rules applied to different components. Sometimes this rules obviously redundant. Sometimes no obviously, but layout seems working well without it.
So, what exactly this rule suppose to do?
If the component is rendering fine without using flex: 1
it is obviously not needed. You might as well want to remove the unwanted style. What flex: 1
does is that it tells the component to occupy as much space as it can.
For example:
<View style={{ flex: 1, backgroundColor: '#cccccc' }}>
<Text>Hi</Text>
</View>
This will span the whole screen.
However, if you place another View at the same level in the DOM, both of the Views will occupy equal space i.e. the screen will be divided in two parts.
Like this:
<View style={{ flex: 1 }}>
<View style={{ flex: 1, backgroundColor: '#cccccc' }}>
<Text>View one</Text>
</View>
<View style={{ flex: 1, backgroundColor: '#eaeaea' }}>
<Text>View two</Text>
</View>
</View>
I agree that flexbox is a little bit confusing. But once you get the hang of it, you'll learn how to manipulate the views.
Edit: Always wrap child components with a parent component in order to avoid potential runtime errors.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With