justifyContent
- React Native course
- Beginner
- Lesson 37/116
- 5 min
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'.
Practice 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>.
Starter code
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
export default function Bar() {
return (
<View>
<Text>Save</Text>
<Text>Cancel</Text>
</View>
);
}
const styles = StyleSheet.create({
// Add the bar style here
});Sample 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' }
});Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Write the centering value
<View style={{ flexDirection: 'row', justifyContent:____}}>
<Text>A</Text>
<Text>B</Text>
</View>
<View style={{ flexDirection: 'row', justifyContent:'center'}}>
<Text>A</Text>
<Text>B</Text>
</View>
Explanation: 'center' centers children on the main axis.
2 Which hugs children to the edges?
justifyContent: ???- 'stretch'
- 'center'
- 'flex-start'
- 'space-between' Correct answer
Explanation: space-between hugs the first and last child to the edges.
3 Match each value to its job
| Term | Meaning |
|---|---|
'flex-start' |
Hug the start |
'center' |
Center |
'space-between' |
Hug edges, split the rest |
'flex-end' |
Hug the end |