apartment-clone/components/ImageCarousel.tsx

113 lines
2.8 KiB
TypeScript

import { StyleSheet, FlatList, Pressable, Image } from 'react-native'
import React from 'react'
import { MaterialCommunityIcons } from '@expo/vector-icons';
import { WIDTH } from '../constants';
import { useState, useRef } from 'react';
//we will be taking in an array of images as the argument
const ImageCarousel = ({ images }:{ images: string[] }) => {
const flatListRef = useRef<FlatList | null>(null)
const viewConfig = { viewAreaCoveragePercentThreshold: 95 };
const [activeIndex, setActiveIndex] = useState(0)
const onViewRef = useRef(({changed}: {changed: any}) => {
if (changed[0].isViewable) {
setActiveIndex(changed[0].index);
}
})
//handle the scrolling of images when the chevrons are pressed
const handlePressLeft = () => {
if (activeIndex === 0)
return flatListRef.current?.scrollToIndex({
animated: false,
index: images.length - 1,
});
flatListRef.current?.scrollToIndex({
index: activeIndex - 1,
});
};
const handlePressRight = () => {
if (activeIndex === images.length - 1)
return flatListRef.current?.scrollToIndex({
animated: false,
index: 0,
});
flatListRef.current?.scrollToIndex({
index: activeIndex + 1,
});
};
return (
<>
{/* Flatlist to scrolll through a single property image */}
<FlatList
style={{
flexGrow: 0
}}
ref={(ref) => (flatListRef.current = ref)}
data={images}
horizontal
showsHorizontalScrollIndicator={false}
snapToAlignment='center'
pagingEnabled
onViewableItemsChanged={onViewRef.current}
viewabilityConfig={viewConfig}
renderItem={({ item }) => (
<Image
source={{ uri: item }}
style={ styles.image }
/>
)}
keyExtractor={(item) => item}
/>
{/* Chevrons */}
<Pressable
style={[
styles.chevron,
{left: 5}
]}
onPress={handlePressLeft}
>
<MaterialCommunityIcons
name="chevron-left"
color="white"
size={45}
/>
</Pressable>
<Pressable
style={[
styles.chevron,
{right: 5}
]}
onPress={handlePressRight}
>
<MaterialCommunityIcons
name="chevron-right"
color="white"
size={45}
/>
</Pressable>
</>
)
}
export default ImageCarousel
const styles = StyleSheet.create({
image: {
height: 225,
width: WIDTH,
borderTopLeftRadius: 5,
borderTopRightRadius: 5
},
chevron: {
position: "absolute",
top: 95
}
})