My carousel is currently working, but it does so with wonky animations. I handle an array of images, where at the beginning and at the end I use the same image. When displaying the final element of the array, it's supposed to go back to the first element without the change being noticed, but there is flickering and sometimes it breaks and runs the animation in reverse to display the first element of the array (It scrolls from finish to start instead of from start to finish).
import { View, SafeAreaView, Animated, Dimensions } from 'react-native';
import { useRef, useEffect } from 'react';
const arrayOfImages = [
{key: 1, Component: SvgImage1 },
{key: 2, Component: SvgImage2 },
{key: 3, Component: SvgImage3 },
{key: 4, Component: SvgImage4 },
{key: 5, Component: SvgImage5 },
{key: 6, Component: SvgImage1 },
]
const { width } = Dimensions.get('screen');
const MyCarousel = () => {
const flatListRef = useRef(null);
let index = 0;
useEffect(() => {
const interval = setInterval(() => {
index = index === arrayOfImages.length - 1 ? 0 : index + 1;
flatListRef.current.scrollToIndex({
index,
animated: true,
});
if (index === arrayOfImages.length - 1) {
setTimeout(() => {
index = 0;
flatListRef.current.scrollToIndex({
index,
animated: false,
});
}, 3400);
}
}, 3500);
return () => clearInterval(interval);
}, []);
return (
<SafeAreaView className="w-full bg-white">
<Animated.FlatList
data={arrayOfImages}
ref={flatListRef}
horizontal
showsHorizontalScrollIndicator={false}
pagingEnabled
keyExtractor={item => `${item.key}`}
renderItem={({ item }) => (
<View
style={{
width,
}}
>
<item.Component style={{ alignSelf: 'center', width }} />
</View>
)}
/>
</SafeAreaView>
);
};
export default MyCarousel;
I think it's related to the timings that the setInterval and setTimeout functions handle, but I can't get it to work smoothly.