Layout with Flexbox
Sprout's plant card has a photo on the left, the name and next watering date in the middle, and a "Watered" button on the right. Every layout like this in React Native is Flexbox. If you know Flexbox from the web, you are most of the way there, but a few defaults are flipped.
The rule
Column by default; justify along the main axis, align across it.
Every View is a flex container. The key properties:
flexDirectionsets the main axis. The default is'column'(top to bottom). On the web it isrow. Use'row'for side-by-side items.justifyContentplaces children along the main axis:'flex-start','center','flex-end','space-between','space-around','space-evenly'.alignItemsplaces children across the main axis:'stretch'(the default),'flex-start','center','flex-end'.flex: 1tells a child to take the remaining space along the main axis. In React Native,flextakes a single number.gapadds space between children without margins on each one.
const styles = StyleSheet.create({
row: {
flexDirection: 'row',
alignItems: 'center',
gap: 12,
padding: 12,
},
photo: { width: 56, height: 56, borderRadius: 8 },
info: { flex: 1 },
});
<View style={styles.row}>
<Image source={{ uri: plant.photoUrl }} style={styles.photo} />
<View style={styles.info}>
<Text>{plant.name}</Text>
<Text>Next water: tomorrow</Text>
</View>
<Button title="Watered" onPress={markWatered} />
</View>The photo has a fixed size, the button takes the width it needs, and info with flex: 1 fills whatever is left. alignItems: 'center' lines all three up vertically.
A screen's outer View usually needs flex: 1 too, so that it fills the whole screen instead of shrinking to its content.
The shortcut
For any layout, answer "which way do they line up?" first. That sets flexDirection and tells you which axis justifyContent and alignItems work on. Then decide who stretches (flex: 1) and who keeps a fixed size.
Which way?
Photo, info, button are side by side.
flexDirection: 'row', so the main axis is horizontal.
The trap is writing justifyContent: 'center' to centre items vertically in a row. In a row the main axis is horizontal, so that centres them sideways. Vertical centring in a row is alignItems.
Drills
Answer fast — trust the rule.
What is the default flexDirection in React Native?
In a View with flexDirection: 'row', which property centres children vertically?
Which style makes the info block fill the space left after the photo and button?
In a default column layout, which property spreads three buttons evenly from top to bottom?
A screen's content only takes up the top third of the phone. What is the likely fix?
Remember
- Column by default;
justifyContentalong the main axis,alignItemsacross it. - Ask "which way do they line up?" first, then choose who stretches.
- Trap: in a row, vertical centring is
alignItems, notjustifyContent.
