Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native Snap Carousel - First Item

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);
      }}
  />
like image 340
Ryan113 Avatar asked Nov 16 '22 21:11

Ryan113


1 Answers

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

)
like image 131
carlosdafield Avatar answered Mar 13 '23 02:03

carlosdafield