react-native-snap-carousel: this._carousel.currentIndex is undefined

How can I store a state with the index of the currently active slide?

I have tried this._carousel.currentIndex, but I get the error undefined is not an object (evaluating 'this._carousel.currentIndex').

I am setting the ref with

<Carousel
  ref={carousel => { this._carousel = carousel; }}

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Comments: 22 (8 by maintainers)

Most upvoted comments

The problem is that you try to use the currentIndex property of the carousel before the Carousel component is rendered and the reference is set.

Make carousel a state variable: const [carousel, setCarousel] = useState(null);

and use setCarousel() to set it in the component. <Carousel ref={c => { setCarousel(c); }} ... />

Then simply check for it’s nullity everytime you use it, so that you catch the errors that might appear before the Carousel component loads and sets the reference.

@hesusdios , simply change the _renderItem to arrow function like _renderItem = ({item, index}) => {} will solve the problem, or renderItem={this._renderItem.bind(this)}.

Hi,

App is crashing with message ‘carouselRef .getPositionIndex is not a function’ when clicking on pagination dots

`const CarouselPage = ({navigation, …props}) => { const [activePage, setActivePage] = useState(0); useEffect( () => { console.log(’ active page : ', activePage) }, [activePage] );

let carouselRef = useRef(); // createRef()

    return(
       <Carousel
          ref={(c) => {carouselRef = c}}
            sliderWidth={screenWidth}
            sliderHeight={screenWidth}
            itemWidth={screenWidth}
            data={entries}
            renderItem={_renderItem}
            onSnapToItem={(index) => { setActivePage(index) }}
        />
         
        <Pagination
          dotsLength={entries.length}
          activeDotIndex={activePage}
          containerStyle={{ backgroundColor: 'rgba(0, 0, 0.6, 0.5)' }}
          dotStyle={{
              width: 10,
              height: 10,
              borderRadius: 5,
              marginHorizontal: 8,
              backgroundColor: 'rgba(255, 255, 255, 0.92)'
          }}
          inactiveDotStyle={{
              // Define styles for inactive dots here
          }}
          inactiveDotOpacity={0.4}
          inactiveDotScale={0.6}
          tappableDots={true}
          tappableDots={ !!carouselRef }
          carouselRef={ carouselRef }
        />
    );

}; ` can anyone help me in fixing this issue

I’ve just tried the following and didn’t face any issue:

<Carousel
  ref={(c) => { this._carousel = c; }}
/>

alert(this._carousel && this._carousel.currentIndex);

Are you positive that the <Carousel /> is mounted when you call this._carousel.currentIndex the first time?