I have made a grid of images using Flatlist. I am loading the images from the web. Currently, all the images are loaded as soon as I navigate to that particular page. What I want is only load those images which are visible on the screen and rest on the scroll. Six images are shown at one time on the screen.
Is it possible to load images on the scroll in Flatlist?
The properties you need to combine are actually initialNumToRender and windowSize. If you only want one screen of images visible at a time, you would use windowSize={1}
. I, personally recommend you use at least windowSize={3} so you have the previous and the next screens rendered buut it really depends on the sizes of the images you are showing.
Also note that the items specified with initialNumToRender
will never be removed. This is to allow "Go to top" functionality. You may or may not want such items.
It is also good to note that you may need to implement some kind of caching of those images. Once you "unrender" them and you need to render them again a new request would be made for them, causing more bandwidth being used on your user's device.
You should be able to do this with the initialNumToRender property on flat list.
so your flatList declaration might be:
<FlatList
initialNumToRender={2}
data={[{key: 'a'}, {key: 'b'}]}
renderItem={({item}) => <Text>{item.key}</Text>}
/>
You can use the Flatlist
as below to load only those images which are in the current viewport.
<FlatList
ref={(view) => (this.parentScrollView = view)}
data={this.state.data}
onScroll={this.handleScroll}
keyExtractor={keyExtractor}
showsVerticalScrollIndicator={false}
bounces={false}
numColumns={3}
renderItem={this.renderItem}
ItemSeparatorComponent={this.ItemSeparatorComponent}
ListEmptyComponent={this.ListEmptyComponent}
//code for optimization and load only visible items
initialNumToRender={8}
maxToRenderPerBatch={2}
onEndReachedThreshold={0.1}
onMomentumScrollBegin={this.onMomentumScrollBegin}
onEndReached={this.onEndReached}
/>
My onEndReached
is:
onEndReached = () => {
console.log('end reached');
if (!this.onEndReachedCalledDuringMomentum) {
console.log('loading more archived products');
this.loadMoreProducts();
this.onEndReachedCalledDuringMomentum = true;
}
}
And onMomentumScrollBegin
is:
onMomentumScrollBegin = () => { this.onEndReachedCalledDuringMomentum = false; }
initialNumToRender
will mount the first 8 items and will never remove them unless the Flatlist
itself doesn't get unmounted. It is helpful to preserve list scrolling performance while fast scrolling the list.
onMomentumScrollBegin
and onEndReachedThreshold
is used to when to load more element for the list. This could be an API call etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With