Anand
Anand

Reputation: 15

FlatList scrollToIndex is scrolling to one index less than the desired (last) index in React Native

I have a FlatList of images and when a new image is added to the data of the FlatList, I want to scroll programatically to the last index. On Android this is working fine, but on iOS, it is scrolling to one less than the last index. Here is my code:

const slider = createRef();

const scrollToIndex = (index) => {
  if (slider.current) {
    slider.current.scrollToIndex({ index: index, animated: true });
  }
};

useEffect(() => {
  scrollToIndex(props.data.length - 1);
}, [props.data]);

And here is my FlatList:

<FlatList
  ref={slider}
  horizontal={true}
  pagingEnabled={true}
  snapToAlignment={"center"}
  decelerationRate={0.99}
  bounces={false}
  contentContainerStyle={props.contentContainerStyle}
  data={props.data}
  showsHorizontalScrollIndicator={false}
  renderItem={({ item, i }) => {
    return React.cloneElement(props.component, {
      width: size.width,
      item: item,
      orientation: props.orientation,
      // onPress: props.onPress,
      index: i % props.data.length,
      active: i === index,
      local: props.local,
    });
  }}
  ItemSeparatorComponent={() => <></>}
  keyExtractor={(item, index) => item.toString() + index}
  onViewableItemsChanged={onViewableItemsChanged}
  viewabilityConfig={viewabilityConfig}
  getItemLayout={(_, index) => ({
    length: size.width,
    offset: size.width * index,
    index,
  })}
  windowSize={1}
  initialNumToRender={1}
  maxToRenderPerBatch={1}
  removeClippedSubviews={true}
  onContentSizeChange={handleContentSizeChange}
/>;

I would greatly appreciate any ideas. Thanks!

Upvotes: 0

Views: 20

Answers (0)

Related Questions