meliorence / react-native-snap-carousel

Swiper/carousel component for React Native featuring previews, multiple layouts, parallax images, performant handling of huge numbers of items, and more. Compatible with Android & iOS.
BSD 3-Clause "New" or "Revised" License
10.37k stars 2.29k forks source link

how to get index of the item, when pagingEnabled #927

Open christopher-18 opened 2 years ago

christopher-18 commented 2 years ago

I want to use pagingEnabled option in Carousel, since it is working as expected and is not giving any performance issue in android. Without using that prop, their is slight delay in manually scrolling the items placed horizontally , but on iOS it working fine.

This is what the initial implementation was.

<Carousel
         onSnapToItem={(slideIndex: number) => {
          setSlideIndex(slideIndex);
         }}
        data={data}
        renderItem={renderSliderItem}
        sliderWidth={carouselWidth}
        itemWidth={carouselWidth}
        loop={true}
        slideStyle={{ width: carouselWidth }}
        autoplay={autoPlay}
        autoplayDelay={scrollInterval}
        autoplayInterval={scrollInterval}
        useScrollView
        enableSnap={true}
        shouldOptimizeUpdates={true}
        loopClonesPerSide={5}
        enableMomentum={true}
        decelerationRate={0.9}
        activeSlideAlignment="center"
        removeClippedSubviews={true}
        inactiveSlideScale={1}
        inactiveSlideOpacity={1}
        inactiveSlideShift={1}
        lockScrollWhileSnapping={true}
        />

But it not working. so added changed it to following

<Carousel
        // onSnapToItem={(slideIndex: number) => {
        //   setSlideIndex(slideIndex);
        // }}
        data={data}
        renderItem={renderSliderItem}
        sliderWidth={carouselWidth}
        itemWidth={carouselWidth}
        loop={true}
        slideStyle={{ width: carouselWidth }}
        autoplay={autoPlay}
        autoplayDelay={scrollInterval}
        autoplayInterval={scrollInterval}
        useScrollView
        enableSnap={true}
        shouldOptimizeUpdates={true}
        loopClonesPerSide={5}
        enableMomentum={true}
        decelerationRate={0.9}
        activeSlideAlignment="center"
        removeClippedSubviews={true}
        inactiveSlideScale={1}
        inactiveSlideOpacity={1}
        inactiveSlideShift={1}
        activeSlideOffset={0.5}
        lockScrollWhileSnapping={true}
        pagingEnabled
        onMomentumScrollEnd={onScrollEnd}
        />
   But onScrollEnd function is not giving correct index. 

let onScrollEnd = (e) => {
    let pageNumber = Math.min(
      Math.max(Math.floor(e?.nativeEvent?.contentOffset?.y / winWidth + 0.5) + 1, 0),
      data?.length
    );
    console.log(pageNumber);

  };

Please suggest. Stuck here.