When I needed to implement a carousel in my app, I found that most of the available libraries were either outdated, unmaintained, had unresolved issues, or were unnecessarily heavy.
Building a custom carousel in React Native is an excellent way to enhance your app's visual appeal and interactivity. In this blog, we’ll walk through creating a carousel from scratch, featuring auto-scroll functionality using React Native's Animated and Reanimated libraries. We’ll also add a sleek pagination system with animated dots and smooth image transitions for an elegant user experience.
Overview
In this tutorial, we'll cover the following:
- Setting up the Custom Carousel component.
- Using Reanimated for smooth animations and interpolations.
- Auto-scrolling functionality to rotate between images automatically.
- Building a Pagination system with animated dot indicators.
What We'll Build:
- A horizontally scrolling carousel with animated transitions.
- Automatic scrolling that pauses when the user interacts with the carousel.
- Pagination dots that update based on the currently visible item.
Let's get started!
1. Setting Up the Carousel Component
We begin by creating the CustomCarousel
component, which will house the core logic of our carousel. The main elements include:
-
Animated.FlatList
for rendering the items. - An auto-scrolling mechanism using
setInterval
. - Reanimated's
scrollTo
anduseSharedValue
for animating the transitions.
/* eslint-disable react-native/no-inline-styles */
import React, { useEffect, useRef, useState } from 'react';
import { StyleSheet, View, useWindowDimensions } from 'react-native';
import Animated, {
scrollTo,
useAnimatedRef,
useAnimatedScrollHandler,
useDerivedValue,
useSharedValue,
} from 'react-native-reanimated';
import { hpx } from '../../helpers';
import Pagination from './Pagination';
import RenderItem from './RenderItem';
import { animals } from './constants';
const CustomCarousel = () => {
const x = useSharedValue(0);
const [data, setData] = useState(animals);
const { width } = useWindowDimensions();
const [currentIndex, setCurrentIndex] = useState(0);
const [paginationIndex, setPaginationIndex] = useState(0);
const ref = useAnimatedRef();
const [isAutoPlay, setIsAutoPlay] = useState(true);
const interval = useRef();
const offset = useSharedValue(0);
console.log('CURRENT_CAROUSEL_ITEM👉', paginationIndex);
const onViewableItemsChanged = ({ viewableItems }) => {
if (viewableItems[0].index !== undefined && viewableItems[0].index !== null) {
setCurrentIndex(viewableItems[0].index);
setPaginationIndex(viewableItems[0].index % animals.length);
}
};
const viewabilityConfig = {
itemVisiblePercentThreshold: 50,
};
const viewabilityConfigCallbackPairs = useRef([{ viewabilityConfig, onViewableItemsChanged }]);
const onScroll = useAnimatedScrollHandler({
onScroll: (e) => {
x.value = e.contentOffset.x;
},
onMomentumEnd: (e) => {
offset.value = e.contentOffset.x;
},
});
useDerivedValue(() => {
scrollTo(ref, offset.value, 0, true);
});
useEffect(() => {
if (isAutoPlay === true) {
interval.current = setInterval(() => {
offset.value += width;
}, 4000);
} else {
clearInterval(interval.current);
}
return () => {
clearInterval(interval.current);
};
}, [isAutoPlay, offset, width]);
return (
<View style={styles.container}>
<Animated.FlatList
ref={ref}
style={{ height: hpx(194), flexGrow: 0 }}
onScrollBeginDrag={() => {
setIsAutoPlay(false);
}}
onScrollEndDrag={() => {
setIsAutoPlay(true);
}}
onScroll={onScroll}
scrollEventThrottle={16}
horizontal
bounces={false}
pagingEnabled
showsHorizontalScrollIndicator={false}
viewabilityConfigCallbackPairs={viewabilityConfigCallbackPairs.current}
onEndReached={() => setData([...data, ...animals])}
onEndReachedThreshold={0.5}
data={data}
keyExtractor={(_, index) => `list_item${index}`}
renderItem={({ item, index }) => {
return <RenderItem item={item} index={index} x={x} />;
}}
/>
<Pagination paginationIndex={paginationIndex} />
</View>
);
};
export default CustomCarousel;
const styles = StyleSheet.create({
container: {
flex: 1,
},
buttonContainer: {
justifyContent: 'center',
alignItems: 'center',
flexDirection: 'row',
gap: 14,
},
});
2. Pagination Component
The pagination component displays dots to indicate the current active slide. Each dot changes in opacity depending on the current index of the carousel.
import React from 'react';
import { StyleSheet, View } from 'react-native';
import { hpx } from '../../helpers';
import Dot from './Dot';
import { animals } from './constants';
const Pagination = ({ paginationIndex }) => {
return (
<View style={styles.container}>
{animals.map((_, index) => {
return <Dot index={index} key={index} paginationIndex={paginationIndex} />;
})}
</View>
);
};
export default Pagination;
const styles = StyleSheet.create({
container: {
flexDirection: 'row',
marginTop: hpx(16),
justifyContent: 'center',
alignItems: 'center',
},
});
3. Dot Component
The Dot
component handles the appearance of each individual dot in the pagination system. It changes its style based on whether the dot is active (current index) or not.
import React from 'react';
import { StyleSheet, View } from 'react-native';
import { Colors } from '../../assets';
import { hpx, wpx } from '../../helpers';
const Dot = ({ index, paginationIndex }) => {
return <View style={paginationIndex === index ? styles.dot : styles.dotOpacity} />;
};
export default Dot;
const styles = StyleSheet.create({
dot: {
backgroundColor: Colors.white,
height: hpx(3),
width: wpx(12),
marginHorizontal: 2,
borderRadius: 8,
},
dotOpacity: {
backgroundColor: Colors.white,
height: hpx(3),
width: wpx(12),
marginHorizontal: 2,
borderRadius: 8,
opacity: 0.5,
},
});
4. RenderItem Component
The RenderItem
component displays each carousel item. It utilizes Reanimated's interpolate
function to animate the opacity of the items as they scroll.
import React from 'react';
import { StyleSheet, useWindowDimensions, View } from 'react-native';
import Animated, { Extrapolation, interpolate, useAnimatedStyle } from 'react-native-reanimated';
import { hpx, nf, SCREEN_WIDTH, wpx } from '../../helpers/Scale';
const RenderItem = ({ item, index, x }) => {
const { width } = useWindowDimensions();
const animatedStyle = useAnimatedStyle(() => {
const opacityAnim = interpolate(
x.value,
[(index - 1) * width, index * width, (index + 1) * width],
[-0.3, 1, -0.3],
Extrapolation.CLAMP
);
return {
opacity: opacityAnim,
};
});
return (
<View style={{ width }}>
<Animated.Image
resizeMode="cover"
source={{ uri: item.image }}
style={[styles.titleImage, animatedStyle]}
/>
</View>
);
};
export default RenderItem;
const styles = StyleSheet.create({
titleImage: {
width: SCREEN_WIDTH - wpx(32), // adjust the width of the image and horizontal padding
height: hpx(194),
alignSelf: 'center',
borderRadius: nf(16),
},
});
5. Auto-Scrolling
The auto-scroll feature is implemented with the help of setInterval
. This method ensures that the carousel moves automatically from one slide to the next every 4 seconds. If the user interacts with the carousel by dragging, the auto-scroll pauses.
6. Constant file
export const animals = [
{ text: 'cat', image: 'https://i.imgur.com/CzXTtJV.jpg' },
{ text: 'dog', image: 'https://i.imgur.com/OB0y6MR.jpg' },
{ text: 'cheetah', image: 'https://farm2.staticflickr.com/1533/26541536141_41abe98db3_z_d.jpg' },
{ text: 'piano', image: 'https://farm4.staticflickr.com/3224/3081748027_0ee3d59fea_z_d.jpg' },
// { text: 'apple', image: 'https://farm8.staticflickr.com/7377/9359257263_81b080a039_z_d.jpg' },
// { text: 'flower', image: 'https://farm9.staticflickr.com/8295/8007075227_dc958c1fe6_z_d.jpg' },
// { text: 'mushroom', image: 'https://farm2.staticflickr.com/1449/24800673529_64272a66ec_z_d.jpg' },
// { text: 'coffee', image: 'https://farm4.staticflickr.com/3752/9684880330_9b4698f7cb_z_d.jpg' },
];
7. Conclusion
In this tutorial, we built a custom carousel using React Native's FlatList, along with Reanimated for smooth animations and interpolations. We added a pagination system with animated dots, auto-scrolling functionality, and ensured that user interaction would pause and resume the auto-scroll feature.
With these components, you can extend the carousel to include other features like dynamic content, clickable items, and more sophisticated animations. React Native's flexibility with Reanimated allows for highly customizable carousels with minimal performance cost, which is great for creating visually engaging mobile apps.
Feel free to try this out in your project, and customize the styles and behavior to match your design needs!
Top comments (1)
that so amazing component, it work well in LTR but in RTL it doesn't work. can you please check and update new one