flex
- React Native course
- Beginner
- Lesson 39/116
- 5 min
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.
Practice 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} />.
Starter code
import React from 'react';
import { View, StyleSheet } from 'react-native';
export default function Split() {
return (
<View>
<View />
<View />
</View>
);
}
const styles = StyleSheet.create({
// Add row and half styles here
});Sample 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 }.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 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 Correct answer
- Gives a one-time width
- Hides the child
Explanation: flex: 1 gives the child all remaining free space.
2 Write the flexible space property
<View style={{ flexDirection: 'row' }}>
<View style={{ width: 80 }} />
<View style={{____: 1 }} />
</View>
<View style={{ flexDirection: 'row' }}>
<View style={{ width: 80 }} />
<View style={{flex: 1 }} />
</View>
Explanation: 1 takes the remaining free space.
3 Match each flex value to its behavior
| Term | Meaning |
|---|---|
flex: 0 |
Not flexible, fixed |
flex: 1 |
Takes the remaining space |
flex: 2 |
Gets twice the share |
width: 80 |
Fixed pixel width |