yogesh kumar
yogesh kumar

Reputation: 103

How to make a horizontal FlatList with React Native?

I am trying to align those white circles row-wise and I have written the same thing in the code but these circles are getting aligned column-wise, someone can help please.

My Item component:

const Item = ({ item }) => (
  <View style={styles.citiesContainer}>
    <View>
      <Text style={styles.cities}>{item}</Text>
    </View>
  </View>
);

const styles = StyleSheet.create({
  citiesContainer: {
    display: "flex",
    flexDirection: "row",
    flexWrap: "nowrap",
    overflow: "hidden",
    height: 120,
    width: "100%",
    justifyContent: "space-evenly",
    alignContent: "center",
    backgroundColor: "red",
  },
  cities: {
    fontSize: 10,
    flex: 1,
    color: "black",
    width: 100,
    height: 100,
    borderRadius: 50,
    backgroundColor: "#f0f0f0",
  },
});

Where I am rendering it:

const renderItem = ({ item }) => ( <Item title={item} /> ); 
<FlatList
  data={cities}
  renderItem={renderItem}
  keyExtractor={item => item}      
/>

Check the image below to see what I am explaining:

enter image description here

Upvotes: 0

Views: 2814

Answers (1)

Youssouf Oumar
Youssouf Oumar

Reputation: 45865

In order to have items on a row, all you need is to add horizontal={true} on FlatList. Like so:

 <FlatList
   data={cities} 
   renderItem={renderItem}
   keyExtractor={item => item.id} 
   horizontal={true} 
 />

Since you have const renderItem = ({ item }) => (<Item title={item} />), in Item you should be getting title as part of props. And finally change styles object as below:

const Item = ({ title }) => (
  <View style={styles.city}>
    <Text>{title}</Text>
  </View>
);

const styles = StyleSheet.create({
  city: {
    fontSize: 10,
    color: "black",
    width: 100,
    height: 100,
    borderRadius: 50,
    backgroundColor: "#f0f0f0",
  },
});

Upvotes: 1

Related Questions