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)
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] );
}; ` can anyone help me in fixing this issue
I’ve just tried the following and didn’t face any issue:
Are you positive that the
<Carousel />
is mounted when you callthis._carousel.currentIndex
the first time?