Created
February 4, 2023 00:14
-
-
Save RichardSPrins/a33d185eada671e19b18ef605334887e to your computer and use it in GitHub Desktop.
useSlider Hook
This file contains hidden or 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 { useState, useCallback, useEffect } from 'react'; | |
import useEmblaCarousel from 'embla-carousel-react'; | |
import { EmblaOptionsType } from 'embla-carousel-react'; | |
export const useSlider = (options?: EmblaOptionsType) => { | |
const [isPrevButtonEnabled, setIsPrevButtonEnabled] = useState<boolean>(false); | |
const [isNextButtonEnabled, setIsNextButtonEnabled] = useState<boolean>(false); | |
const [activeSlideIndex, setActiveSlideIndex] = useState<number>(0); | |
const [scrollSnaps, setScrollSnaps] = useState<Array<number>>([]); | |
const [sliderRef, emblaAPI] = useEmblaCarousel({ | |
...options, | |
}); | |
const goToPrevious = useCallback(() => emblaAPI && emblaAPI.scrollPrev(), [emblaAPI]); | |
const goToNext = useCallback(() => emblaAPI && emblaAPI.scrollNext(), [emblaAPI]); | |
const goTo = useCallback(index => emblaAPI && emblaAPI.scrollTo(index), [emblaAPI]); | |
const onSelect = useCallback(() => { | |
if (!emblaAPI) return; | |
setActiveSlideIndex(emblaAPI.selectedScrollSnap()); | |
setIsPrevButtonEnabled(emblaAPI.canScrollPrev()); | |
setIsNextButtonEnabled(emblaAPI.canScrollNext()); | |
}, [emblaAPI]); | |
useEffect(() => { | |
if (!emblaAPI) return; | |
onSelect(); | |
setScrollSnaps(emblaAPI.scrollSnapList()); | |
emblaAPI.on('select', onSelect); | |
return () => { | |
emblaAPI.off('select', onSelect); | |
}; | |
}, [emblaAPI, onSelect]); | |
return { | |
sliderRef, | |
carouselMethods: emblaAPI, | |
data: { | |
isPrevButtonEnabled, | |
isNextButtonEnabled, | |
activeSlideIndex, | |
scrollSnaps, | |
}, | |
actions: { | |
goToPrevious, | |
goToNext, | |
goTo, | |
}, | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment