React Native
justifyContent
Learn main-axis alignment with justifyContent.
justifyContent
justifyContent decides how children are distributed along the main axis. With flexDirection: 'row' the main axis is horizontal; with 'column' it is vertical. Common values: 'flex-start' (hug the start), 'center' (center them), 'space-between' (even gaps), 'flex-end' (hug the end).
For example, in a button bar justifyContent: 'space-between' sends the first button left, the last button right, and splits the gap evenly. These values control the main axis of the container; for the cross axis use alignItems.
What does space-between do?
justifyContent: 'space-between' hugs the first child to the start, the last child to the end, and splits the gap between evenly. With three toolbar buttons, Save sits left, Cancel right, Help exactly in the middle.
The similar 'space-around' gives every child equal space but the children at the ends approach the edge with half space. 'space-evenly' makes every gap (including the edges) equal. Mobile design most often uses 'space-between' and 'center'.
Exercise Write a button bar
Fill the empty StyleSheet.create block. Define a style named bar with flexDirection: 'row', justifyContent: 'space-between'. The component returns a <View style={styles.bar}> containing <Text>Save</Text> and <Text>Cancel</Text>.
Show example solution
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
export default function Bar() {
return (
<View style={styles.bar}>
<Text>Save</Text>
<Text>Cancel</Text>
</View>
);
}
const styles = StyleSheet.create({
bar: { flexDirection: 'row', justifyContent: 'space-between' }
});
Test yourself
-
Write the centering value
<View style={{ flexDirection: 'row', justifyContent:____}}>
<Text>A</Text>
<Text>B</Text>
</View>
Show answer
<View style={{ flexDirection: 'row', justifyContent:'center'}}>
<Text>A</Text>
<Text>B</Text>
</View>
-
Which hugs children to the edges?
justifyContent: ???
- 'stretch'
- 'center'
- 'flex-start'
- 'space-between'
Show answer
'space-between' — space-between hugs the first and last child to the edges.
-
Match each value to its job
- 'flex-start'
- Hug the start
- 'center'
- Center
- 'space-between'
- Hug edges, split the rest
- 'flex-end'
- Hug the end
Next lesson: alignItems