Skip to content

Instantly share code, notes, and snippets.

@janicduplessis
Created April 27, 2024 17:24
Show Gist options
  • Save janicduplessis/bf507742b3ea082cf8c818d0b7b84590 to your computer and use it in GitHub Desktop.
Save janicduplessis/bf507742b3ea082cf8c818d0b7b84590 to your computer and use it in GitHub Desktop.
import React, {useRef, useState} from 'react';
import {
Button,
FlatList,
SafeAreaView,
Text,
View,
} from 'react-native';
const generateUniqueKey = () => `_${Math.random().toString(36).substr(2, 9)}`
const initialData = Array.from(Array(15).keys()).map(n => ({
id: generateUniqueKey(),
value: n,
}))
function ListItem({item}) {
const color = `hsl(${item.value * 10}, 75%, 85%)`;
return (
<View
style={{
backgroundColor: color,
height: 100,
}}>
<Text>List item: {item.value}</Text>
</View>
);
}
export default function FlatListRepro() {
const numToAdd = 1;
const [numbers, setNumbers] = useState(initialData);
const ref = useRef();
const addAbove = () => {
setNumbers(prev => {
const additionalNumbers = Array.from(Array(numToAdd).keys())
.map(n => ({
id: generateUniqueKey(),
value: prev[0].value - n - 1,
}))
.reverse();
return additionalNumbers.concat(prev);
});
};
const addBelow = () => {
setNumbers(prev => {
const additionalNumbers = Array.from(Array(numToAdd).keys())
.map(n => ({
id: generateUniqueKey(),
value: prev[prev.length - 1].value + n + 1,
}))
return prev.concat(additionalNumbers);
});
};
return (
<SafeAreaView style={{flex: 1}}>
<View style={{flexDirection: 'row', alignItems: 'center'}}>
<Button title="Add Above" onPress={addAbove} />
<Button title="Add Below" onPress={addBelow} />
</View>
<View>
<FlatList
ref={ref}
data={numbers}
renderItem={({item}) => <ListItem item={item} />}
maintainVisibleContentPosition={{
minIndexForVisible: 0,
}}
onStartReached={() => {
console.log('onStartReached');
}}
onEndReached={() => {
console.log('onEndReached');
}}
/>
</View>
</SafeAreaView>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment