Reputation: 342
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 ?
Upvotes: 7
Views: 3633
Reputation: 1
You can use to Flatlist prop named "ListHeaderComponent" to add any component at the beginning of your Flatlist. https://reactnative.dev/docs/flatlist#listheadercomponent
Upvotes: -2
Reputation: 491
The way I did it is by inverting FlatList using the inverted
prop, and also reversing my list. In this way, the top of FlatList will be at the bottom with last item in my array is visible there.
When user scrolls to the top onEndReached
is triggered, and I add new items to the beginning of my array and they will be added to the top of FlatList with out changing the current visible item at the top.
Upvotes: 0
Reputation: 25353
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,
}}
/>
Upvotes: 8