React Native
flexWrap
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.
Exercise 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.
Show example 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 }
});
Test yourself
-
Write the wrapping value
<View style={{ flexDirection: 'row', flexWrap:____}}>
<Text>A</Text>
<Text>B</Text>
<Text>C</Text>
</View>
Show answer
<View style={{ flexDirection: 'row', flexWrap:'wrap'}}>
<Text>A</Text>
<Text>B</Text>
<Text>C</Text>
</View>
-
Match each value to its behavior
- 'wrap'
- Move to a new line
- 'nowrap'
- Overflow on one line
- flexDirection: 'row'
- Lay out horizontally
- flex: 1
- Take the free space
-
What happens when flexWrap is omitted?
<View style={{ flexDirection: 'row' }}>
{/* 10 tags */}
</View>
- Children wrap automatically
- Children stack vertically
- Children overflow on one line
- Children are hidden
Show answer
Children overflow on one line — The default is 'nowrap'; children overflow on one line.
Next lesson: Summary - Flexbox