forked from cmcaboy/imageCarouselExample
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBackgroundCarousel.js
106 lines (97 loc) · 2.52 KB
/
BackgroundCarousel.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import * as React from "react";
import { StyleSheet, View, ScrollView, Dimensions, Image } from "react-native";
const DEVICE_WIDTH = Dimensions.get("window").width;
class BackgroundCarousel extends React.Component {
scrollRef = React.createRef();
constructor(props) {
super(props);
this.state = {
selectedIndex: 0
};
this.scrollRef = React.createRef();
}
componentDidMount = () => {
setInterval(() => {
this.setState(
prev => ({
selectedIndex:
prev.selectedIndex === this.props.images.length - 1
? 0
: prev.selectedIndex + 1
}),
() => {
this.scrollRef.current.scrollTo({
animated: true,
x: DEVICE_WIDTH * this.state.selectedIndex,
y: 0
});
}
);
}, 3000);
};
setSelectedIndex = event => {
const contentOffset = event.nativeEvent.contentOffset;
const viewSize = event.nativeEvent.layoutMeasurement;
// Divide the horizontal offset by the width of the view to see which page is visible
const selectedIndex = Math.floor(contentOffset.x / viewSize.width);
this.setState({ selectedIndex });
};
render() {
const { images } = this.props;
const { selectedIndex } = this.state;
return (
<View style={{ height: "100%", width: "100%" }}>
<ScrollView
horizontal
pagingEnabled
onMomentumScrollEnd={this.setSelectedIndex}
ref={this.scrollRef}
>
{images.map(image => (
<Image
style={styles.backgroundImage}
source={{ uri: image }}
key={image}
/>
))}
</ScrollView>
<View style={styles.circleDiv}>
{images.map((image, i) => (
<View
style={[
styles.whiteCircle,
{ opacity: i === selectedIndex ? 0.5 : 1 }
]}
key={image}
active={i === selectedIndex}
/>
))}
</View>
</View>
);
}
}
const styles = StyleSheet.create({
backgroundImage: {
height: "100%",
width: Dimensions.get("window").width
},
circleDiv: {
position: "absolute",
bottom: 15,
display: "flex",
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
width: "100%",
height: 10
},
whiteCircle: {
width: 6,
height: 6,
borderRadius: 3,
margin: 5,
backgroundColor: "#fff"
}
});
export { BackgroundCarousel };