Mike K
Mike K

Reputation: 6473

Map array image elements horizontally

I'm trying to map images in an array horizontally, but they're being mapped vertically no matter what I do.

    const numberOfRows = Math.ceil(images.length / 3); 

    const result = Array(numberOfRows)
      .fill()
      .map((_, rowIndex) => (
        <View key={rowIndex}>
          {images
            .slice(rowIndex * 5, rowIndex * 5 + 5)
            .map((image, imageIndex) => (
              <TouchableOpacity
                key={imageIndex}
                onPress={() => alert("image pressed!")}
              >
                <Image
                  source={{
                    uri:
                      "https://miro.medium.com/max/814/1*Cxm5opOziPF5iavnDSYHLg.png"
                  }}
                  style={{ width: 100, height: 100 }}
                />
              </TouchableOpacity>
            ))}
        </View>
      ));

What am I doing wrong here?

Upvotes: 0

Views: 679

Answers (3)

Nirmalsinh Rathod
Nirmalsinh Rathod

Reputation: 5186

You just need to add flexDirection to your View.

<View key={rowIndex} style={{flex: 1, flexDirection: 'row'}}>
...
</View>

You can read more about flexDirection from here.

Upvotes: 0

Tim
Tim

Reputation: 10709

The standard flex-direction of a View is vertical. By adding flexDirection: 'row' to your parent View, you can overwrite this behavior.

Code

<View key={rowIndex} style={{flexDirection: 'row'}}>
...
</View>

Working Snack:

https://snack.expo.io/rygY2Vb3H

Upvotes: 1

Kishan Bharda
Kishan Bharda

Reputation: 5690

By default react-native View flex-direction was column. So to align vertically add flexDirection: 'row' to view :

<View key={rowIndex} style={{flex: 1, flexDirection: 'row', flexWrap: 'wrap'}}>
... // your image map code
</View>

Upvotes: 0

Related Questions