diff --git a/README.md b/README.md index 1495136..ca8724c 100644 --- a/README.md +++ b/README.md @@ -128,6 +128,8 @@ From version **4.0.0** it has been moved to *Functional component* and fix separ | itemContainerStyle | Style for each carousel container item | View style | {} | No | | onScrollEnd | Fired while scrollview end of scrolling | Function | ()=> {} | No | | initialIndex | Initial starting focused item of list | Number | 0 | No | +| autoPlay | Adds autoplay functionality | Boolean | false | No | +| autoPlayInterval | Use with autoPlay. Sets the interval of the slides when autoPlay is activated. | Number | 4000 | No | diff --git a/src/carousel.js b/src/carousel.js index 29b174b..cc5ed36 100644 --- a/src/carousel.js +++ b/src/carousel.js @@ -39,6 +39,8 @@ function Carousel(props, ref) { inActiveOpacity = 0.8, inverted = false, initialIndex = 0, + autoPlay = false, + autoPlayInterval = 4000, bounces = true, showsHorizontalScrollIndicator = false, keyExtractor = (item, index) => index.toString(), @@ -50,6 +52,7 @@ function Carousel(props, ref) { } = props; const scrollViewRef = useRef(null); const currentIndexRef = useRef(initialIndex); + const [isAutoPlay, setIsAutoPlay] = useState(autoPlay); const scrollXRef = useRef(0); const scrollXBeginRef = useRef(0); const xOffsetRef = useRef(new Animated.Value(0)); @@ -60,6 +63,19 @@ function Carousel(props, ref) { const containerStyle = [styles.container, { width: containerWidth }, style]; const dataLength = data ? data.length : 0; + let interval; + useEffect(() => { + if (!isAutoPlay) { + return; + } + interval = setInterval(() => { + generateAutoPlay() + }, autoPlayInterval); + return () => { + clearInterval(interval); + } + }, [isAutoPlay]) + useConstructor(() => { setScrollHandler(); }); @@ -111,6 +127,12 @@ function Carousel(props, ref) { }); } + function generateAutoPlay() { + scrollToIndex( + (currentIndexRef.current + 1) % (data.length - 1) + ); + } + function handleOnScrollBeginDrag() { onScrollBeginDrag && onScrollBeginDrag(); scrollXBeginRef.current = scrollXRef.current; @@ -134,6 +156,14 @@ function Carousel(props, ref) { } } + function handleTouchStart() { + setIsAutoPlay(false); + } + + function handleTouchEnd() { + setIsAutoPlay(true); + } + function getItemTotalMarginBothSide() { const compensatorOfSeparatorByScaleEffect = (1 - inActiveScale) * itemWidth; return separatorWidth - compensatorOfSeparatorByScaleEffect / 2; @@ -254,6 +284,8 @@ function Carousel(props, ref) { {...otherProps} ref={scrollViewRef} data={data} + onTouchStart={handleTouchStart} + onTouchEnd={handleTouchEnd} style={containerStyle} horizontal={true} inverted={inverted}