vtambourine
vtambourine

Reputation: 2149

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?

Upvotes: 5

Views: 4462

Answers (2)

Mihir
Mihir

Reputation: 3902

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.

Upvotes: 8

Brett DeWoody
Brett DeWoody

Reputation: 62871

For layout React Native uses flexbox because display: flex; is extremely well-suited for creating responsive layouts across various screen sizes and devices. All the attribute names and values are listed in the React Native docs.

In other words, instead of using display: block with various floats your layout should be created using flexbox rules.

Modus Create did a nice tutorial on Flexbox in React Native.

Specifically, that rule:

flex: 1 

is telling the element to grow to fill the available space.

Upvotes: 0

Related Questions