Add data to begining of FlatList without changing position

Viewed 1738

I'm trying to implement an "onBeginReached" like props in flatlist. I would like to append some data at the begining of my data array in a transparent way to user.

So using this flatList :

const App = () => {
  const flatListRef = useRef(null);
  const [data, setData] = useState(generateData(20));

  const renderItem = ({ item }) => {
  console.log(item);
  return (
    <View style={styles.itemContainer}>
      <Text style={styles.itemText}>{item}</Text>
    </View>
  );
};

  const handleMomentumScroll = (event) => {
    console.log("Momentum end")
    const xOffset = event.nativeEvent.contentOffset.x;
    const index = Math.round(xOffset / 30);

    if (index < 1) {
      setData([-10 ,-9, -8, -7, -6,-5, -3, -2, -1, ...data]);
    }
  };

  return (
    <FlatList
      style={{ width: 200, alignSelf: 'center', marginTop: 150 }}
      initialScrollIndex={10}
      horizontal
      data={data}
      snapToAlignment={'start'}
      decelerationRate={'fast'}
      snapToInterval={30}
      getItemLayout={(data, index) => ({
         length: 30,
         offset: 30 * index,
         index,
      })}
      keyExtractor={(item, index) => index.toString()}
      renderItem={renderItem}
      onMomentumScrollEnd={handleMomentumScroll}
    />
  );
};

const styles = StyleSheet.create({
  itemContainer: {
    alignItems: 'center',
    justifyContent: 'center',
    width: 30,
    height: 30,
    borderRadius: 15,
    backgroundColor: 'blue',
  },
  itemText: {
    color: 'white',
  },
});

(https://snack.expo.io/GUblotbZc)

If I scroll to the index 0, it'll unshift my new data to my data array. But, it'll scroll automatically to the first index of the new data array. I would like to keep the current position when unshifting new data to the array.

There is a way to impletement that behaviour ?

1 Answers

here is demo: https://snack.expo.io/@nomi9995/flatlisttest

use maintainVisibleContentPosition props for preventing auto scroll in IOS but unfortunately, it's not working on android but good news is pull request has come for android and need to merge with react native.

<FlatList
  ref={(ref) => { this.chatFlatList = ref; }}
  style={styles.flatList}
  data={this.state.items}
  renderItem={this._renderItem}
  maintainVisibleContentPosition={{
     minIndexForVisible: 0,
  }}
/>
Related