Reputation: 1764
I have the following array of objects (just example, actual cases could be a lot more)
const items = [{/* for user 1 */}, {/* for user 2 */}, ... {/* for user 10 */}];
Im displaying the array as list in Flatlist
<FlatList
data={items}
renderItem={renderItem}
keyExtractor={item => item.id}
initialNumToRender={20}
/>
Where renderItem is like this
const renderItem = ({ item: user }) => (
<TouchableOpacity
activeOpacity={1}
style={styles.items}
onPress={() => {clickMe(user)}}
>
<UserAvatar url={user.url} />
<Text style={styles.userName}>{ user.name }</Text>
</TouchableOpacity>
);
All is working well and fine so far, and the list can display properly.
But say if i want to display user 9 as the first item on the list, how would i do that?
i tried doing it like this
const ninthUser = items.find( i => i.id === 9 );
const listWithoutNinth = items.filter( i => i.id !== 9 );
const listWithNinthAsFirstItem = [ ninthUser, ...listWithoutNinth ];
And pass listWithNinthAsFirstItem
to the data prop of the Flatlist but somehow it wouldn't work.
Upvotes: 1
Views: 965
Reputation: 1397
You should involve state.
const [ sortedItems, setSortedItems ] = useState([])
const startSort = () => {
const ninthUser = items.find( i => i.id === 9 );
const listWithoutNinth = items.filter( i => i.id !== 9 );
const listWithNinthAsFirstItem = [ ninthUser, ...listWithoutNinth ];
setSortedItems(listWithNinthAsFirstItem)
}
useEffect(() => {
if (items) {
startSort()
}
}, [items])
and then in FlatList pass data as sortedItems
<FlatList data={sortedItems} renderItem={renderItem}
keyExtractor={item => item.id} initialNumToRender={20} />
Upvotes: 1