6

I am trying to get my React Snap Carousel to load on the desired index. Currently when the carousel loads it loads the first index instead of the one I tell it to with FirstItem. When I refresh the screen or save in my code editor the carousel snaps to the firstItem(index) that I am referring to. Below is my code. Also I have seen the many cards for this and they point to https://github.com/archriss/react-native-snap-carousel/blob/master/doc/KNOWN_ISSUES.md#unreliable-first-item. For the life of me though I cannot figure out how to get it working properly. I appreciate any help. Thank you.

  <Carousel
    layout={'default'}
    ref={c => {
    this._carousel = c;
    }}
    useScrollView={true}
    data={this.getDaysArray() ? this.getDaysArray() : []}
    renderItem={this.renderItem.bind(this)}
    sliderWidth={Platform.OS === 'ios' ? 375 : 392}
    itemWidth={Platform.OS === 'ios' ? 310 : 332}
    firstItem={22}
    initialScrollIndex={23}
    onLayout={() => {
      this._carousel.snapToItem(22);
      }}
  />
Ryan113
  • 676
  • 1
  • 10
  • 27

3 Answers3

1

I had this same problem and for some reason when I never put an empty list in there it worked. It worked when you always put the data with N elements where firstItem < N. So something like this worked for me.

if (this.getDaysArray().length===0){
    return (<View> 
              <Text>Loading screen or what ever</Text>
            <View/>)
}

return  (
<Carousel
    layout={'default'}
    ref={c => {
    this._carousel = c;
    }}
    useScrollView={true}
    data={this.getDaysArray() ? this.getDaysArray() : []}
    renderItem={this.renderItem.bind(this)}
    sliderWidth={Platform.OS === 'ios' ? 375 : 392}
    itemWidth={Platform.OS === 'ios' ? 310 : 332}
    firstItem={22}
    initialScrollIndex={23}
    onLayout={() => {
      this._carousel.snapToItem(22);
      }}
  />

)
carlosdafield
  • 1,479
  • 5
  • 16
0

I used firstitem, getItemLayout, initialNumToRender, and initialScrollIndex many times, but it didn't work. I finally used loopClonesPerSide and set its value to data.length and started displaying from first item.

loopClonesPerSide= { data.length }

0

If you are RTL, you can use a LTR View for the container:

 <View style={{
            writingDirection: 'rtl',
            display: 'flex',
            flexDirection: 'row-reverse',}}>
            <Carousel....
Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77