flexWrap
- React Native course
- Beginner
- Lesson 40/116
- 5 min
Learn wrapping behavior with flexWrap.
flexWrap
By default flex children stay on one line; they overflow even when they do not fit. With flexWrap: 'wrap' the children that do not fit move to the next line. It is ideal for tags, chips and small image galleries.
Example: inside <View style={{ flexDirection: 'row', flexWrap: 'wrap' }}> five tags split as three on the first line and two on the next. The default is 'nowrap'; without an explicit 'wrap' children overflow.
A tag cloud
Picture a tag cloud: each tag has a different width and must fit the screen. With flexDirection: 'row' and flexWrap: 'wrap' together, tags flow left to right and drop to the next line when they do not fit. The gap property is handy for spacing.
Example: { flexDirection: 'row', flexWrap: 'wrap', gap: 8 }. Each tag keeps its own size while 8 pixels of space stays between rows. On mobile gap is supported by modern React Native; older versions need marginRight on each child.
Practice Write a tag cloud
Fill the empty StyleSheet.create block. Define a style named cloud with flexDirection: 'row', flexWrap: 'wrap', gap: 8. The component returns a <View style={styles.cloud}> containing three <Text>: Apple, Pear, Cherry.
Starter code
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
export default function TagCloud() {
return (
<View>
<Text>Apple</Text>
<Text>Pear</Text>
<Text>Cherry</Text>
</View>
);
}
const styles = StyleSheet.create({
// Add the cloud style here
});Sample solution
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
export default function TagCloud() {
return (
<View style={styles.cloud}>
<Text>Apple</Text>
<Text>Pear</Text>
<Text>Cherry</Text>
</View>
);
}
const styles = StyleSheet.create({
cloud: { flexDirection: 'row', flexWrap: 'wrap', gap: 8 }
});Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Write the wrapping value
<View style={{ flexDirection: 'row', flexWrap:____}}>
<Text>A</Text>
<Text>B</Text>
<Text>C</Text>
</View>
<View style={{ flexDirection: 'row', flexWrap:'wrap'}}>
<Text>A</Text>
<Text>B</Text>
<Text>C</Text>
</View>
Explanation: 'wrap' moves overflowing children to a new line.
2 Match each value to its behavior
| Term | Meaning |
|---|---|
'wrap' |
Move to a new line |
'nowrap' |
Overflow on one line |
flexDirection: 'row' |
Lay out horizontally |
flex: 1 |
Take the free space |
3 What happens when flexWrap is omitted?
<View style={{ flexDirection: 'row' }}>
{/* 10 tags */}
</View>- Children wrap automatically
- Children stack vertically
- Children overflow on one line Correct answer
- Children are hidden
Explanation: The default is 'nowrap'; children overflow on one line.