I created a FlatList in React Native.
The data is:
const Friends = [
{
id: 1,
name: 'Alex Lee',
profileImage: require("../Assets/FriendsImages/f1.png"),
followers: '246',
},
{
id: 2,
name: 'Micheal Ulasi',
profileImage: require("../Assets/FriendsImages/f2.png"),
followers: '106',
},
.......
.......
]
export default Friends
FlatList Code
import { StyleSheet, Text, View, TextInput, Image, FlatList, TouchableOpacity } from 'react-native'
import React, { useState } from 'react'
import Friends from '../database/Friends'
const FriendsList = () => {
const [backgroundColor, setBackgroundColor] = useState('#E2E2E2');
const handlePress = () => {
setBackgroundColor(backgroundColor === '#E2E2E2' ? '#5669FF' : '#E2E2E2');
};
return (
<View style={{ marginHorizontal: 24, marginTop: 7, }}>
<FlatList
showsVerticalScrollIndicator={false}
data={Friends}
renderItem={({ item }) =>
<View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }}>
<View style={{ flexDirection: 'row', alignItems: 'center', marginBottom: 16 }}>
<Image style={{...}}
source={item.profileImage}/>
<View>
<Text style={{...}}>{item.name}</Text>
<Text style={{...}}>{item.followers} Folloers</Text>
</View>
</View>
<TouchableOpacity
style={{ backgroundColor: backgroundColor, height: 20, width: 20, borderRadius: 10, }}
onPress={handlePress}>
<View style={{ alignItems: 'center', justifyContent: 'center',height: 20, width: 20, }}>
<Image style={{...}} source={require("../Assets/Icons/TickIcon.png")} />
</View>
</TouchableOpacity>
</View>}
/>
</View>)}
export default FriendsList
Now, I want to change backgroundColor of TouchableOpacity on press. In my case, When i press one it changes backgroundColor of all. But I want only that TouchableOpacity change color which pressed.

To be able to highlight only the selected users from your list, you need to modify your response a little.
Firstly, we will declare a new array at the top of the component.
Also, we will need to use
useState()hook to manage our updated user list.Now, we will use a
useEffecthook through which will insert a new keyisSelectedwith a boolean set tofalseto your friend's list by iterating over your main list. Once the key has been inserted we will push the value to theuserListand then we will set this new array to ourfriendList.Here, I have updated your TouchableOpacity, now we will change the
backgroundColoronly when theisSelectedkey is set to true otherwise we'll show a default color. Also, the same logic will be applied for the visibility of the image. And on press of this view we will callhandlePress()and passitem.idas argument.Keep in mind, this
idwill be used to update theisSelectedkey in yourfriendList.In the
handlePress()we will compare the parameteridwith the array's id and if it matches we will update theisSelectedkey totrueotherwise we will keep the object as it is. Then, we will update ourfriendList.Here's how it will look in action.
Gist