Skip to content

Instantly share code, notes, and snippets.

@RichardSPrins
Created February 4, 2023 00:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RichardSPrins/a33d185eada671e19b18ef605334887e to your computer and use it in GitHub Desktop.
Save RichardSPrins/a33d185eada671e19b18ef605334887e to your computer and use it in GitHub Desktop.
useSlider Hook
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