skip to Main Content

I’m hoping to get help building an Image Grid in React Native.

I’m trying to create an image grid with mapped data from an array. The mapping part is working fine but the images are not being place the way I want.
This is what I’m looking for (images placed where red squares are):
Image grid I'm trying to achive!

This is my code so far:

  <ScrollView style={{flex: 1,  backgroundColor: 'yellow', 
    }} >
        {data.map(image => (
          <View style={styles.viewpic}>
           <Image style={styles.image} source={{uri:image.url }}/>
           </View> 
           ))}
       </ScrollView>
    </SafeAreaView>

This is my CSS:

 viewpic: {
    flex: 1,
    flexWrap:'wrap',
    justifyContent: 'center',
    flexDirection: 'row',
     backgroundColor: 'blue',
  },
  image: {
    justifyContent: 'center',
    height: 115,
    width: 115,
    margin:6,
    backgroundColor: 'red',
  }

This is what I’m currently getting:
Result

So far I tried every single CSS combo I could think but nothing has worked so far.
I also tried FLATLIST but to be honest I wasn’t able to properly convert my current code to "fit" the requirements of Flatlists.

Thanks everyone for your help!
Cheers!

2

Answers


  1. Chosen as BEST ANSWER

    I was able to find the answer! I combined 2 tutorials + a few tricks and got it done!

    First I built my image grid using "FlatList". I found a great tutorial with the step by step here(not my page, not affiliated):Youtube Tutorial At the beginning I was getting the same result until I added "numColumns={ }"

    Here's the code:

    ...
      const numberOfCols = 3
    ...
    return(
    

    .

    <View>
     <FlatList
            data={data}
            keyExtractor={(item, index)=>{return item.date}}
            numColumns={numberOfCols}
            renderItem={({item, index})=>(
              <View style={styles.viewpic}>
                <Image style={styles.image} source={{uri:item.url}}/>
              </View>
            )}
            />
    

    Then I used a bit of the strategy from this tutorial (not my page, not affiliated) : Youtube Tutorial

    I still need to adjust the css so it looks better but I'm happy with it so far.

    Here is the final result:Image grid screenshoot


  2. it’s an HTML mistake.
    In fact, you put the flex-wrap style for each element, that’s why you have one element per line.
    You have to put all the elements inside the flex-wrap div and it will works. I hope it will help you

              <View style={styles.viewpic}>
               {data.map(image => (
               <Image style={styles.image} source={{uri:image.url }}/>
               ))}
              </View> 
           
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search