I am making an album app with react native and want to make FlatList
with images like Instagram. When clicks item of FlatList
, it will navigate to the same item in another screen with different FlatList
. How to do this?
My code:
const RenderItemList = ({item, index}) => {
return (
<Pressable onPress={() => navigation.navigate('detail')}>
<View key={index} style={[index%3!==0 ? {paddingLeft:2} : {paddingLeft:0}, {marginBottom: 2}]}>
<Image style={{width: sizeOfImage, height: sizeOfImage}}
source={{uri : item.uri}}
/>
</View>
</Pressable>
)}
You can use initialScrollIndex
prop from the Flatlist
API. Pass the index as route params to other screen and set initialScrollIndex
to that index.
Example below
<FlatList
data={sampleImages}
keyExtractor={(item) => item.id.toString()}
numColumns={3}
renderItem={({ item, index }) => (
<Pressable
style={{ width: EachWidth, height: EachWidth }}
onPress={() => navigation.navigate('Details', { initialScroll: index })}>
<Image
source={{ uri: item.download_url }}
style={{ width: EachWidth, height: EachWidth }}
/>
</Pressable>
)}
/>
On other screen,
<FlatList
data={sampleImages}
keyExtractor={(item) => item.id.toString()}
initialScrollIndex={route.params.initialScroll || 0} // Use here
renderItem={({ item }) => (
<View style={{ width: ScreenWidth, height: ScreenWidth }}>
<Image
source={{ uri: item.download_url }}
style={{ width: ScreenWidth, height: ScreenWidth }}
/>
</View>
)}
/>