Reputation: 5251
It will be better if I demonstrate with images.
This is what I am trying to achieve. Assume landscape mode tablet size. Let's say I have X amount of elements in array. I want to map it across the row until it has 3 items in a row, then goes down. With bootstrap, I can do something like col-md-4
three times.
Currently I am using native-base
. It has an interesting grid systems, but not exactly what I wanted.
This is what I have right now:
<Grid>
<Row>
{ recipeStore.categories.map((category, index) => {
return (
<Col key={index} style={{height: 300}}>
<Card>
<CardItem>
<Body>
<Text>{ category.name }</Text>
</Body>
</CardItem>
</Card>
</Col>
)
})}
</Row>
</Grid>
How can I get the array iteration to fill out 3 columns then goes to the next row?
Upvotes: 1
Views: 4618
Reputation: 3438
The best way to do this is using the FlatList
it is good in performance and easy to use. And it is recommended for making a list (see this). Additionally you don't need to add any extra package to your project.
You can easily use the FlatList
as below:
_keyExtractor = (item, index) => index;
_renderItem = ({item: category}) => (
<Card>
<CardItem>
<Body>
<Text>{ category.name }</Text>
</Body>
</CardItem>
</Card>
);
render() {
return (
<FlatList
numColumns={3}
data={recipeStore.categories}
keyExtractor={this._keyExtractor}
renderItem={this._renderItem}
/>
);
}
Note: you should use the numColumns
peroperty to define the number of items in each row.
You can see the documentation of FlatList
in here.
Upvotes: 0
Reputation: 5643
You can use flexWrap: 'wrap'
on the parent contain and then use flexBasis
on the children.
import React, { Component } from 'react';
import { View, StyleSheet } from 'react-native';
const ABox = () => <View style={styles.box} />;
export default class App extends Component {
render() {
return (
<View style={styles.container}>
<ABox />
<ABox />
<ABox />
<ABox />
<ABox />
<ABox />
<ABox />
<ABox />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexWrap: 'wrap',
flexDirection: 'row',
paddingTop: 20,
},
box: {
flexBasis: 75,
borderWidth: 1,
borderColor: 'black',
height: 40,
margin: 10,
}
});
Snack: https://snack.expo.io/HkUFUp7ub
Upvotes: 3