UNPKG

@faceless-ui/slider

Version:

A React library for building every kind of slider

53 lines 2.02 kB
import { useCallback, useEffect, useRef } from "react"; export const useScrollToIndex = (args) => { const { sliderState, onSlide, scrollOffset, sliderTrackRef } = args; const animationRef = useRef(undefined); const prevScrollIndex = useRef(undefined); const scrollToIndex = useCallback((incomingSlideIndex) => { const hasIndex = sliderState.slides[incomingSlideIndex]; if (animationRef.current) cancelAnimationFrame(animationRef.current); if (hasIndex && sliderTrackRef.current) { const targetSlide = sliderState.slides[incomingSlideIndex]; const targetSlideRef = targetSlide.ref.current; if (targetSlideRef) { const { offsetLeft } = targetSlideRef; animationRef.current = requestAnimationFrame(() => { if (sliderTrackRef.current) { sliderTrackRef.current.scrollTo({ top: 0, left: (offsetLeft - (scrollOffset || 0)), behavior: 'smooth', }); } }); } if (typeof onSlide === 'function') onSlide(incomingSlideIndex); } }, [ sliderState.slides, onSlide, scrollOffset, sliderTrackRef ]); // auto-scroll to the target index only when "scrollIndex" changes useEffect(() => { if (sliderState.scrollIndex !== undefined && prevScrollIndex.current !== sliderState.scrollIndex) { scrollToIndex(sliderState.scrollIndex); prevScrollIndex.current = sliderState.scrollIndex; } }, [ sliderState.scrollIndex, scrollToIndex, ]); useEffect(() => { () => { if (animationRef.current) { cancelAnimationFrame(animationRef.current); } }; }, []); return null; }; //# sourceMappingURL=useScrollToIndex.js.map