-
-
Save belozer/80e8327ff89e4210123d6807a3b81741 to your computer and use it in GitHub Desktop.
Carousel hook with gestures support
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as React from 'react'; | |
const { default: TinyGesture } = require('tinygesture'); | |
export function useCarousel(itemsLength: number) { | |
const [state, setState] = React.useState({ currentIndex: 0, translateValue: 0 }); | |
const carouselRef = React.useRef<HTMLDivElement>(null); | |
React.useEffect(() => { | |
const gesture = new TinyGesture(carouselRef.current); | |
gesture.on('swiperight', goToPrevItem); | |
gesture.on('swipeleft', goToNextItem); | |
setState({ currentIndex: 0, translateValue: 0 }); | |
return () => gesture.destroy(); | |
}, [itemsLength]); | |
const slideWidth = () => { | |
const element = document.querySelector('.carousel__slide'); | |
if (!element) { | |
return 0; | |
} | |
return element.clientWidth || 0; | |
}; | |
const goToPrevItem = () => setState(prevState => { | |
if (!itemsLength) { | |
return { translateValue: 0, currentIndex: 0 }; | |
} | |
if (prevState.currentIndex === 0) { | |
return prevState; | |
} | |
return { | |
currentIndex: prevState.currentIndex - 1, | |
translateValue: prevState.translateValue + slideWidth(), | |
}; | |
}); | |
const goToNextItem = () => setState(prevState => { | |
if (!itemsLength) { | |
return { currentIndex: 0, translateValue: 0 }; | |
} | |
if (prevState.currentIndex === itemsLength - 1) { | |
return prevState; | |
} | |
return { | |
currentIndex: prevState.currentIndex + 1, | |
translateValue: prevState.translateValue - slideWidth(), | |
}; | |
}); | |
const handleDotClick = (index: number) => { | |
setState(prevState => { | |
if (index === prevState.currentIndex) { | |
return prevState; | |
} | |
const translateValue = index > prevState.currentIndex | |
? -index * slideWidth() | |
: prevState.translateValue + (prevState.currentIndex - index) * slideWidth(); | |
return { currentIndex: index, translateValue }; | |
}); | |
}; | |
return { | |
carouselRef, | |
state, | |
goToPrevItem, | |
goToNextItem, | |
handleDotClick, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment