$ git show auto-carousel
Auto-playing carousel
Slides advance on a timer, pause while you drag, and the pager dots follow the live scroll position.
// Scroll-driven, so Reanimated 4 uses the same scroll handler; the timer is plain React
const { width } = useWindowDimensions();
const ref = useAnimatedRef<Animated.ScrollView>();
const x = useSharedValue(0);
const page = useRef(0);
const dragging = useRef(false);
const onScroll = useAnimatedScrollHandler((e) => {
x.value = e.contentOffset.x;
});
useEffect(() => {
const id = setInterval(() => {
if (dragging.current) return;
page.current = (page.current + 1) % slides.length; // wraps back to the first slide
ref.current?.scrollTo({ x: page.current * width, animated: true });
}, 3000);
return () => clearInterval(id);
}, [width]);
<Animated.ScrollView
ref={ref}
horizontal
pagingEnabled
showsHorizontalScrollIndicator={false}
onScroll={onScroll}
scrollEventThrottle={16}
onScrollBeginDrag={() => { dragging.current = true; }}
onMomentumScrollEnd={(e) => {
dragging.current = false;
page.current = Math.round(e.nativeEvent.contentOffset.x / width);
}}>
{slides.map((s) => <Image key={s.id} source={s.image} style={{ width, height: 200 }} />)}
</Animated.ScrollView>
function Dot({ i, x, width }) {
const style = useAnimatedStyle(() => {
const p = x.value / width;
return {
width: interpolate(p, [i - 1, i, i + 1], [8, 22, 8], Extrapolation.CLAMP),
opacity: interpolate(p, [i - 1, i, i + 1], [0.4, 1, 0.4], Extrapolation.CLAMP),
};
});
return <Animated.View style={[styles.dot, style]} />; // height 8, borderRadius 4
}
<View style={styles.dots}>
{slides.map((s, i) => <Dot key={s.id} i={i} x={x} width={width} />)}
</View>