I would like help building an image grid in React Native.
I'm trying to create an image grid using mapped data in an array. The mapping part works fine, but the images are not placed the way I want. This is what I'm looking for (image placed where the red square is):
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 currently get:
So far I've tried every CSS combination I can think of, but nothing has worked so far. I also tried FLATLIST, but to be honest, I couldn't convert my current code properly to "fit" the requirements of Flatlists.
Thank you for your help! cheers!
P粉3302320962024-02-22 00:48:20
This is an HTML error. In fact, you set the flex-wrap style for each element, which is why there is only one element per row. You have to put all elements into a flex-wrap div for it to work. hope it helps you
{data.map(image => ( ))}
P粉1352928052024-02-22 00:05:05
I found the answer! I combined some tips from 2 tutorials and got it done successfully!
First, I built the image grid using "FlatList". I found a great step-by-step tutorial here (not my page, not affiliated): YouTube Tutorials At first I got the same results until I added "numColumns={ }"
code show as below:
... const numberOfCols = 3 ... return(
.
{return item.date}} numColumns={numberOfCols} renderItem={({item, index})=>( )} />
Then I used some strategies from this tutorial (not my page, not affiliated): Youtube Tutorial
I still need to tweak the CSS to make it look better, but so far I'm happy with it.