Course contentsShow
← React Native
Lesson 250 of 1,5554. Flexbox and Native StylingFree lesson

Flexible Space Distribution

Control how components expand to fill remaining parent space using flex weights.

In this lesson, you will learn how to make your UI elements intelligently "stretch" to fill empty space using the flex property.

The Problem: Fixed vs. Flexible

When you build a layout, components often have a fixed size (like a width of 100). But what happens when the screen size changes or you have extra space left over? If you leave it blank, your app looks disconnected. If you try to hard-code widths, it breaks on different devices.

Using the flex Weight

Instead of guessing sizes, you assign a flex weight. Think of flex as a "priority score" for how a component should divide the available empty space inside a parent container.

If you have a parent container with a height of 500, and you place two child components inside:

  1. If the first child has flex: 1 and the second has flex: 1, they will each take exactly 50% of the space.
  2. If the first has flex: 1 and the second has flex: 3, the total "weight" is 4. The first gets 1/4 of the space, and the second gets 3/4.

Here is how it looks in code:

<View style={{ flex: 1, flexDirection: 'row' }}>
  <View style={{ flex: 1, backgroundColor: 'red' }} />
  <View style={{ flex: 3, backgroundColor: 'blue' }} />
</View>

In this example, the blue box will always be three times wider than the red box, regardless of whether the user is on a small phone or a large tablet. The flex property tells React Native: "Look at how much space is left over, divide it into these proportions, and fill it up."

Why it Matters

Using flex is the secret to responsive design. It ensures your layouts are fluid and that no awkward gaps are left at the bottom or sides of your screen. By focusing on proportions rather than pixels, your app will naturally adapt to any device you throw at it.

Key Takeaway: The flex property acts as a weight that dictates how much remaining space a component claims relative to its siblings, ensuring your UI remains perfectly proportional on any screen size.