react-native-snap-carousel when swiping it renders all items each time - react-native

I'm using react-native-snap-carousel and I have large data, and it feel quite laggy when swiping each time.
I debugged the renderItem method and it's rendering each time on swipe. Should this happen normally or what ?
Is there a way to solve this issue ?
const [activeSlide, setActiveSlide] = useState(0);
const renderItem = useCallback(
({ item, index }) => {
return (
<CarouselImage
ad={ad}
item={item}
index={index}
showImage={showImage}
/>
);
},
[ad, showImage]);
return ad?.videos?.length > 0 || ad?.images?.length > 0 ? (
<View style={styles.container}>
<Carousel
initialNumToRender={selectedItems.length}
maxToRenderPerBatch={5}
ref={carouselRef}
swipeThreshold={5}
itemWidth={wp(375)}
data={selectedItems}
sliderWidth={wp(375)}
enableMomentum={false}
lockScrollWhileSnapping
renderItem={renderItem}
onSnapToItem={(index) => setActiveSlide(index)}
/>
<Pagination
activeOpacity={1}
tappableDots={true}
animatedDuration={100}
inactiveDotScale={0.4}
inactiveDotOpacity={0.4}
carouselRef={carouselRef}
dotStyle={styles.dotStyle}
activeDotIndex={activeSlide}
dotsLength={selectedItems.length}
containerStyle={styles.pagination}
dotContainerStyle={styles.dotContainer}
inactiveDotStyle={styles.inactiveDotStyle}
/>
</View>

Related

How can I change the numColumns of Flatlist when changing the orientation

I created the function name getOrientation() and put it at useEffect so that whenever I rotate the device, it will rerender the component and show me which orientation the device is.
I also created the variable to determine the orientation by using hook
getOrientation()
const [orientation, setOrientation] = useState("")
const window = useWindowDimensions()
const getOrientation = () => {
if (window.height < window.width) {
setOrientation("LANDSCAPE")
} else {
setOrientation("PORTRAIT")
}
return orientation
}
at useEffect
useEffect(() => {
getOrientation()
})
console.log(orientation)
My problem is that I want to set the numsColumns = 2 in Flatlist (LANDSCAPE) and equals to 1 for the portrait mode but the error popup telling me that I cannot change the numColumns on the fly. What should I do ?
Here is my flatlist
<View style={styles.container}>
<FlatList
contentContainerStyle={{
paddingLeft: insets.left,
paddingRight: insets.right,
}}
data={dishes.dishes}
numColumns={orientation == "LANDSCAPE" ? 2 : 1}
renderItem={({ item, index }) => (
<Tile
style={styles.tileItem}
key={index}
title={item.name}
caption={item.description}
onPress={() => navigation.navigate('Dishdetail_Screen', { dishId: item.id })} // passing infor from one to another screen
// chevron={false}
featured
imageSrc={{
uri: baseUrl + item.image
}}
/>
)}
keyExtractor={item => item.id.toString()} />
</View>
This creepy error
enter image description here
P/s: I'm the fresh React-Native developer. Thanks everyone who is checking my problems
Try adding a key prop to your Flatlist like so with the value being ur orientation:
<FlatList
key={orientation} // add key prop here
contentContainerStyle={{
paddingLeft: insets.left,
paddingRight: insets.right,
}}
data={dishes.dishes}
numColumns={orientation == "LANDSCAPE" ? 2 : 1}
renderItem={({ item, index }) => (
<Tile
style={styles.tileItem}
key={index}
title={item.name}
caption={item.description}
onPress={() => navigation.navigate('Dishdetail_Screen', { dishId: item.id })} // passing infor from one to another screen
// chevron={false}
featured
imageSrc={{
uri: baseUrl + item.image
}}
/>
)}
keyExtractor={item => item.id.toString()} />

FlatList search bar does not persist keyboard React Native

I'm fetching data from an API and implementing search in a FlatList but the keyboard dismisses automatically after every key-press.
I'm refering this article but implementing it in a Functional Component.
const renderHeader = () => {
return <SearchBar
placeholder="Type Here..."
lightTheme
round
onChangeText={text => searchFilterFunction(text)}
value={value}
autoCorrect={false} />;
}
const searchFilterFunction = (text) => {
setValue(text);
const newData = APIData.filter(item => {
const itemData = `${item.name.toUpperCase()}`;
const textData = text.toUpperCase();
return itemData.includes(textData);
});
setData(newData);
}
return (
<FlatList
keyExtractor={(item) => item._id}
data={data}
ItemSeparatorComponent={renderSeparator}
ListHeaderComponent={renderHeader}
ListFooterComponent={renderFooter}
onRefresh={handleRefresh}
refreshing={refreshing}
renderItem={({ item }) => (
<Card>
<Card.Content style={{ flexDirection: "row" }}>
<Text>{"Name: " + item.name}</Text>
<Text>{"Status: " + (item.isaccepted ? "Accepted" : "Pending")}</Text>
<Text>{"ID: " + item.id}</Text>
</Card.Content>
</Card>
)} />
)
Thanks in advance.
I was doing same thing, adding search bar as a header to FlatList. Unfortunately, this also updates the header when you update the flatlist data when search filtering is complete and hence focusing out of SearchBar. At the end, due to time constraints, I ended up putting SearchBar at the top of FlatList.
Try rendering your ListHeaderComponent as JSX element directly, instead of using callback
<FlatList
ListHeaderComponent={
<View>
<Text>I am the header</Text>
</View>
}
...props
/>

Pausing videos on FlatList horizontal when swiping

I'm able to console log the viewable items, when swiping when using FlatList, but I was wondering how I can manage pausing the video. Or if there's a better way in doing so?
This is the RenderItem function component
const RenderItem = (props) => {
const [paused, setPaused] = useState(true);
const togglePlay = () => setPaused(prev => !prev);
return (
<View>
{props.is_video ? (
<>
<Video
paused={paused}
repeat
source={{uri: props.mediaUrl}}
/>
<TouchableWithoutFeedback onPress={togglePlay}>
<View>
{paused ? <Icon
size={180}
name="play"
type="FontAwesome"
style={{opacity: 0.7, color: '#cccccc'}}
/> : null}
</View>
</TouchableWithoutFeedback>
</>
) : (
<Image source={{uri: props.mediaUrl}} />
)}
</View>
);
};
Then in another function, I have this:
const Post = (props) => {
const onViewRef = useRef((viewableItems)=> {console.log(viewableItems)});
const viewConfigRef = useRef({ viewAreaCoveragePercentThreshold: 50 });
return (
<View style={{flex: 1}}>
<View>
<FlatList
onViewableItemsChanged={onViewRef.current}
viewabilityConfig={viewConfigRef.current}
data={props.navigation.state.params.media}
snapToAlignment={'center'}
horizontal
decelerationRate={'fast'}
pagingEnabled
renderItem={({item}) => <RenderItem {...item} />}
keyExtractor={item => item.mediaUrl}
/>
</View>
</View>
);
};
I'm able to press the video and it'll Play or Pause. When I'm swiping right now, the videos continue to play. I want to be able to ensure that when swiping, the video played will become paused now.
You can lift the pause/playing state to the parent component (Post). Since at most 1 video should be playing at anytime, the state can simply store the item ID (or mediaUrl if you are using that as the key/ID) that is currently playing.
In RenderItem:
<Video paused={props.paused} ... />
<TouchableWithoutFeedback onPress={props.onTogglePlay}>
In Post (you can use useCallback for the anonymous functions):
const [activeVideo, setActiveVideo] = useState(null);
...
<FlatList onViewableItemsChanged={() => setActiveVideo(null)} .../>
...
<RenderItem
paused={activeVideo !== item.mediaUrl}
onTogglePlay={() =>
setActiveVideo(item.mediaUrl === activeVideo ? null : item.mediaUrl)
}
{...item}
/>
You may also store the ref to the active video and pause the video through that ref.

FlatList Weird Behavior after appending new data - multiple automatic scrolling

I have a list of data that shows posts feed, whenever user scrolls, the list automatically scrolls multiple times up or down which results in a very bad UX
tried the workaround provided here:
https://stackoverflow.com/questions/43611485/prevent-flatlist-from-scrolling-when-new-items-are-added#=
but it doesn't seem to work for me.
<FlatList
keyboardDismissMode = 'on-drag'
keyboardShouldPersistTaps = 'always'
getItemLayout={(data, index) => (
{length: 575, offset: 575 * index, index}
)}
onScroll = {(event) => {
this.flatListOffset = event.nativeEvent.contentOffset.y
this.setState({
scrollOffset: event.nativeEvent.contentOffset.y
})
}}
contentContainerStyle={{
flexGrow: 1,
width: Dimensions.get('window').width
}}
refreshControl={
<RefreshControl
progressViewOffset={120}
refreshing={this.state.refreshing}
onRefresh={this._onRefresh.bind(this)}
/>
}
ref={(feedView) => (this.feedView = feedView)}
data={this.state.feed}
onEndReached={() => {
if (this.state.hasNextPage && !this.state.loadingMore) {
this.paginateFeed()
}
}}
ListHeaderComponent={this._renderCirclesBar}
ListEmptyComponent={this._renderEmptyState}
ListFooterComponent={() =>
!this.state.loadingMore ? null : (
<ActivityIndicator color="#2962FF" size="large" />
)
}
keyExtractor={this._keyExtractor}
renderItem={this._renderItem}
/>
then at some point:
this.setState({ feed: this.state.feed.concat(....) })
a GIF explaining the issue:
https://gifyu.com/image/9gDD
User PureComponent for rendering and set prop disableVirtualization={true} in flatlist

Difference between FlatList and VirtualizedList

I am new in react native, and am confused about the difference between FlatList and VirtualizedList.
So,
What are the differences between FlatList and VirtualizedList ?
When should I use each ?
The <FlatList> is a performant interface for rendering basic, flat lists.
On the other side, the <VirtualizedList> is a base implementation of the <FlatList> and <SectionList> components, which are also better documented. In general, <VirtualizedList> should only really be used if you need more flexibility than FlatList provides, e.g. for use with immutable data instead of plain arrays.
FlatList example:
const App = () => {
const renderItem = ({ item }) => (
<Item title={item.title} />
);
return (
<SafeAreaView style={styles.container}>
<FlatList
data={DATA}
renderItem={renderItem}
keyExtractor={item => item.id}
/>
</SafeAreaView>
);
}
VirtualizedList example:
const App = () => {
return (
<SafeAreaView style={styles.container}>
<VirtualizedList
data={DATA}
initialNumToRender={4}
renderItem={({ item }) => <Item title={item.title} />}
keyExtractor={item => item.key}
getItemCount={getItemCount}
getItem={getItem}
/>
</SafeAreaView>
);
}
More info:
https://reactnative.dev/docs/virtualizedlist
https://reactnative.dev/docs/flatlist