React Native
flex
Learn flexible sizing with flex: 1.
flex
flex decides how much of the container's free space a child takes. flex: 1 gives a child all remaining free space. Two siblings each with flex: 1 split the free space in two; the one with flex: 2 gets twice the share.
This property is written on the child, not the container. For example, to split two boxes inside a View equally you give each one flex: 1. For a fixed sidebar plus a flexible main area you write width: 80 on the sidebar and flex: 1 on the main area.
Exercise Split two boxes equally
Fill the empty StyleSheet.create block. Define row and half styles. row: flexDirection: 'row'. half: flex: 1, backgroundColor: 'skyblue'. The component returns a <View style={styles.row}> containing two <View style={styles.half} />.
Show example solution
import React from 'react';
import { View, StyleSheet } from 'react-native';
export default function Split() {
return (
<View style={styles.row}>
<View style={styles.half} />
<View style={styles.half} />
</View>
);
}
const styles = StyleSheet.create({
row: { flexDirection: 'row' },
half: { flex: 1, backgroundColor: 'skyblue' }
});
Proportional splitting
flex behaves like a ratio: the sum of the children's flex values defines the free space, and each child takes its share. Give three siblings flex: 1, flex: 2, flex: 1 and the total is 4; the first and third get 25%, the middle one gets 50%.
For a mix of fixed and flexible, write the fixed width with width and the flexible remainder with flex: 1. For an 80 pixel menu on the left and content filling the rest on the right, use { width: 80 } and { flex: 1 }.
Test yourself
-
What does flex: 1 do?
<View style={{ flexDirection: 'row' }}>
<View style={{ flex: 1 }} />
<View style={{ flex: 1 }} />
</View>
- Makes the child 1 pixel
- Takes the remaining free space
- Gives a one-time width
- Hides the child
Show answer
Takes the remaining free space — flex: 1 gives the child all remaining free space.
-
Write the flexible space property
<View style={{ flexDirection: 'row' }}>
<View style={{ width: 80 }} />
<View style={{____: 1 }} />
</View>
Show answer
<View style={{ flexDirection: 'row' }}>
<View style={{ width: 80 }} />
<View style={{flex: 1 }} />
</View>
-
Match each flex value to its behavior
- flex: 0
- Not flexible, fixed
- flex: 1
- Takes the remaining space
- flex: 2
- Gets twice the share
- width: 80
- Fixed pixel width
Next lesson: flexWrap