Reputation: 5182
I have used a ListView to list some items but they're all left aligned. How to center align them without using another View wrapping the ListView?
Code for the ListView
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderItem}
style={styles.listView}
/>
ListView Styling
listView: {
paddingTop: 20,
paddingBottom: 20,
}
How to do this? Thanks in advance.
Upvotes: 10
Views: 23241
Reputation: 2055
You can solve this by using the contentContainerStyle
ListView prop to apply the needed flexbox styles directly to the ListView's internal container, like so:
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderItem}
contentContainerStyle={styles.listView}
/>
// ...
var styles = StyleSheet.create({
listView: {
flex: 1,
justifyContent: 'center',
},
});
Likewise, this also works when you need both axes centered by adding alignItems: 'center'
to the listView
style.
Upvotes: 33
Reputation: 4033
this.renderItem should be a function which renders the row. Your row should set the styles it needs. So something like this:
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderItem}
style={styles.listView}
/>
renderItem: (item) {
<ItemRow item={item} />
}
And then in the ItemRow component:
render: () {
<View style={flexDirection: 'row', justifyContent: 'center'}>
<Text>{this.props.item.name</Text>
</View>
}
Upvotes: 5