I'm trying to create a FlatList that keeps the current scroll position locked and does not change by new items that are inserted at the top of the list.
I've created an expo snack to demonstrate my intention.
The snack presents a ScrollView with green items, and a black item at the end. When the app launch it scrolls to the bottom of the list. After five seconds 10 items are inserted at the top, and the scroll position is changing according to the total size of these items.
This is the code of the expo snack:
import React, { Component } from 'react';
import { View, FlatList } from 'react-native';
const renderItem = ({ item }) => {
let backgroundColor;
if (item == 10) {
backgroundColor = "black"
}
else {
backgroundColor = item % 2 == 0 ? 'green' : 'blue'
}
return (
<View
style={{
width: 200,
height: 50,
backgroundColor,
margin: 10,
}}
/>
);
};
const MyList = class extends Component {
componentDidMount() {
setTimeout(() => this.ref.scrollToEnd({ animated: false }), 500);
}
render() {
return (
<FlatList
ref={r => this.ref = r}
data={this.props.data}
renderItem={this.props.renderItem}
/>
);
}
};
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
items: [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 10],
};
}
componentDidMount() {
const items = [...this.state.items];
items.unshift(1, 1, 1, 1, 1, 1, 1, 1, 1, 1);
setTimeout(() => this.setState({ items }), 5000);
}
render() {
return <MyList renderItem={renderItem} data={this.state.items} />;
}
}
I want to keep the scroll position locked, meaning - when items are inserted the scroll position will not change (or at least in a way the user doesn't know anything happened)
Is there a way to do it with the current API of FlatList and ScrollView? What's needed to be implemented to achieve this feature?