Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center Align contents of a ListView in react native

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.

like image 855
Nimila Hiranya Avatar asked Nov 18 '15 07:11

Nimila Hiranya


People also ask

How do I center an item within a react native 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.

How do you align items in Center in react?

js, set its display property to flex and its alignItems and justifyContent properties to center . The div's content will be horizontally and vertically centered.


2 Answers

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.

like image 132
John Whitley Avatar answered Oct 23 '22 02:10

John Whitley


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>
}
like image 5
eyal83 Avatar answered Oct 23 '22 01:10

eyal83