Align vertically Icon and Text in ListView – React Native

I want to make a ListView and each row should contain an Icon and a Text. But I need them to be vertically aligned.

The code:

export default class SettingsPage extends Component {

constructor() {
  super();
  const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
  this.state = {
    dataSource: ds.cloneWithRows([
      {
        iconName: 'bell',
        title: 'bell'
      },
      {
        iconName: 'map-marker',
        title: 'map'
      },
    ]),
  };
}

_renderRow(rowData) {
  return (
    <View style={{borderBottomWidth:1, padding:20}}>
    <Text>
    <Icon name={rowData.iconName} size={40}/>
    <Text style={{fontSize:25}}>   {rowData.title}</Text>
    </Text>
  </View>
  );
}

render() {
  return (
    <ListView
      dataSource={this.state.dataSource}
      renderRow={this._renderRow}
    />
  );
}
}

The above code generates:

Components are not aligned

in which the components are not aligned.

How can I solve this?

Answer

Try something like this:

_renderRow(rowData) {
  return (
    <View style={{borderBottomWidth:1, padding:20, flex: 1, flexDirection: 'row'}}>
    <View style={{flex: 1}}>
      <Icon name={rowData.iconName} size={40}/>
    </View>
    <View style={{flex: 5}}>
      <Text style={{fontSize:25}}>   {rowData.title}</Text>
    </View>
  </View>
  );
}

Tweak the flex value of the <View> wrapping the text element for a result more to your liking.

Leave a Reply

Your email address will not be published. Required fields are marked *