Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native and { flex: 1 }

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?

like image 458
vtambourine Avatar asked Mar 12 '23 22:03

vtambourine


1 Answers

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.

like image 97
Mihir Avatar answered Mar 24 '23 18:03

Mihir