How to reduce space between Items in horizontal Flatlist

miladsolgi picture miladsolgi · Jan 17, 2019 · Viewed 7.1k times · Source

I use horizontal FlatList of React native and use ListItem and Card of Native base in it to render my List Items. It works but the space between items is too big and I can't reduce it.

this is FlatList :

<FlatList
   horizontal data={this.props.data}
   showsHorizontalScrollIndicator={false}
   keyExtractor={item => item.title}
   renderItem={this.renderItem}
 />

and this is renderItem:

renderItem = ({ item }) => {
      return (
        <ListItem onPress={() => 
                 this.props.navigate(this.state.navigateTO,{
                    id:item['id'],
                    title:item['title'],
                    top_image:item['top_image'],
                    token:this.state.token,
                    lan:this.state.lan,
                    type:this.state.type,
                 }
                  )} >
          <Card style={{height:320, width: 200}}>
              <CardItem  cardBody>
                 <Image source={{uri:item['top_image']}}
                 style={{height:200, width: 200}}/>
              </CardItem>
              <CardItem>
                <Left>
                  <Body>
                  <Text >{item['title']}</Text>
                  <Text note>{item['city']} </Text>
                </Body>
              </Left>
            </CardItem>
          </Card>
       </ListItem>
      );
  };

Answer

Andrew picture Andrew · Jan 21, 2019

It is the ListItem that you have wrapped the Card in that is causing the massive padding that you are seeing. If you remove that you will find that the cards are much closer together.

You could then wrap the card in a TouchableOpacity component, or similar, that would allow you to have your touch event and it would also allow you more control over the space of the items by adjusting the styling on the TouchableOpacity.

Remember to import it

import { TouchableOpacity } from 'react-native';

This is how you could update your renderItem

renderItem = ({ item }) => {
  return (
    <TouchableOpacity onPress={() => 
      this.props.navigate(this.state.navigateTO,{
          id:item['id'],
          title:item['title'],
          top_image:item['top_image'],
          token:this.state.token,
          lan:this.state.lan,
          type:this.state.type,
          }
      )} 
      style={{ padding: 10 }} // adjust the styles to suit your needs
      >
      <Card style={{height:320, width: 200}}>
          <CardItem  cardBody>
              <View
              style={{height:200, width: 200, backgroundColor:'green'}}/>
          </CardItem>
          <CardItem>
            <Left>
              <Body>
              <Text >{item['title']}</Text>
              <Text note>{item['city']}</Text>
            </Body>
          </Left>
        </CardItem>
      </Card>
      </TouchableOpacity>
  );
}