Display `this._carousel.currentIndex`
I don't understand currentIndex.
If I put it inside an onPress method, it works as it should, but I am not able to print it in a <Text>.
It says that this._carousel is undefined.
I am defining this._carousel with
<Carousel
ref={carousel => { this._carousel = carousel; }}
...
See the code below.
elements.map((el, i) => {
return (
<TouchableOpacity onPress={() => alert(this._carousel.currentIndex)}>
<Text>{this._carousel.currentIndex}</Text>
</TouchableOpacity>
)
})
I have the same issue too! Any ideas?
Easiest solution is not to use the ref.
The reason it doesn't work, is the component itself doesn't get re-rendered, which means that it will always display the value at render time.
A better solution would be to use onSnapToItem to set state inside the component that uses the carousel. Something like this, (not tested, just writing from memory)
class MyThing extends React.PureComponent {
state = {
currentIndex: 0,
}
changeIndex = (currentIndex) => {
this.setState({ currentIndex });
}
render() {
return (
<View>
<Carousel onSnapToItem={this.changeIndex} />
<Text>{this.state.currentIndex</Text>
</View>
}
}
Think that should do it...
Thank you! It works.
I didn't have time to answer this before today, so many thanks to @benjdlambert for shining in and explaining things thoroughly!
Thanks!
Use onBeforeSnapToItem instead of onSnapToItem
Use onBeforeSnapToItem instead of onSnapToItem
The last project does not execute this programmatically;