I am learning react native and in all the tutorials i see ListView has been used with only 1 items per row. I have not used ListView, though. I have only 6 items that has to
You can use a FlatList and set to it the numColumns={2}
prop and style={{ flexDirection: 'column' }}
.
In my case I'm working with 3 cols:
FlatList with numColumns={3}
The correct way to do it would be with flexBasis
, with a value set to (1/n)%
where n
is the desired # of rows > 0. For two rows:
.parent {
flex: 1;
flexWrap: 'wrap';
flexDirecton: 'row';
}
.child {
flexBasis: '50%';
}
You can try the flat list from react native. where in you can specific the number of columns and also can mention the vertical direction or horizontal direction. Sample code:
<FlatList
data={this.props.data}
keyExtractor={this._keyExtractor} //has to be unique
renderItem={this._renderItem} //method to render the data in the way you want using styling u need
horizontal={false}
numColumns={2}
/>
Refer https://facebook.github.io/react-native/docs/flatlist.html for more.
If you want to make the grid view trully responsive about the device width import Dimesions:
import {
StyleSheet,
Text,
...
Dimensions,
} from 'react-native';
And change the gridItem width for this:
gridItem: {
margin: 5,
width: Dimensions.get('window').width / 2.2, //Device width divided in almost a half
height: 150,
justifyContent: 'center',
alignItems: 'center',
},
Also you can change the image width to be the same or less as the gridItem.
To make a 2 row grid using ListView
you could use this code as an example:
renderGridItem( item ){
return (<TouchableOpacity style={styles.gridItem}>
<View style={[styles.gridItemImage, justifyContent:'center', alignItems:'center'}]}>
<Text style={{fontSize:25, color:'white'}}>
{item.fields.name.charAt(0).toUpperCase()}
</Text>
</View>
<Text style={styles.gridItemText}>{item.fields.name}</Text>
</TouchableOpacity>
);
}
renderCategories(){
var listItems = this.dsinit.cloneWithRows(this.state.dataSource);
return (
<ScrollView style={{backgroundColor: '#E8E8E8', flex: 1}} >
<ListView
contentContainerStyle={styles.grid}
dataSource={listItems}
renderRow={(item) => this.renderGridItem(item)}
/>
</ScrollView>
);
}
const styles = StyleSheet.create({
grid: {
justifyContent: 'center',
flexDirection: 'row',
flexWrap: 'wrap',
flex: 1,
},
gridItem: {
margin:5,
width: 150,
height: 150,
justifyContent: 'center',
alignItems: 'center',
},
gridItemImage: {
width: 100,
height: 100,
borderWidth: 1.5,
borderColor: 'white',
borderRadius: 50,
},
gridItemText: {
marginTop: 5,
textAlign:'center',
},
});
Change styles to choose how many rows you want to see on screen. This code is responsive.