react-native-snap-carousel icon indicating copy to clipboard operation
react-native-snap-carousel copied to clipboard

Display `this._carousel.currentIndex`

Open mazing opened this issue 9 years ago • 7 comments

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>
  )
})

mazing avatar Aug 19 '17 10:08 mazing

I have the same issue too! Any ideas?

NikitaKis avatar Aug 20 '17 15:08 NikitaKis

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...

benjdlambert avatar Aug 20 '17 17:08 benjdlambert

Thank you! It works.

NikitaKis avatar Aug 20 '17 18:08 NikitaKis

I didn't have time to answer this before today, so many thanks to @benjdlambert for shining in and explaining things thoroughly!

bd-arc avatar Aug 21 '17 22:08 bd-arc

Thanks!

ricarrrdoaraujo avatar Mar 29 '19 13:03 ricarrrdoaraujo

Use onBeforeSnapToItem instead of onSnapToItem

hussainhspl avatar Nov 19 '19 06:11 hussainhspl

Use onBeforeSnapToItem instead of onSnapToItem

The last project does not execute this programmatically;

algate avatar Sep 28 '21 07:09 algate