React Native Change Background Color on Press

103 views Asked by At

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.

enter image description here

1

There are 1 answers

0
Vibhor On BEST ANSWER

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.

let userList = [];

Also, we will need to use useState() hook to manage our updated user list.

const [friendList, setFriendList] = useState([]);

Now, we will use a useEffect hook through which will insert a new key isSelected with a boolean set to false to your friend's list by iterating over your main list. Once the key has been inserted we will push the value to the userList and then we will set this new array to our friendList.

  useEffect(() => {
    Friends?.forEach((val) => {
      userList?.push({ ...val, isSelected: false });
      setFriendList(userList);
    });
  }, []);

Here, I have updated your TouchableOpacity, now we will change the backgroundColor only when the isSelected key 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 call handlePress() and pass item.id as argument.

               <TouchableOpacity
                  style={{
                    backgroundColor:
                      item?.isSelected === true ? "#5669FF" : "#E2E2E2",
                    height: 20,
                    width: 20,
                    borderRadius: 10,
                  }}
                  onPress={() => handlePress(item.id)}
                >
                  <View
                    style={{
                      alignItems: "center",
                      justifyContent: "center",
                    }}
                  >
                    {item?.isSelected === true ? (
                      <Image
                        resizeMode="contain"
                        style={{ height: 20, width: 20 }}
                        source={require("../../images/blue_tick.png")}
                      />
                    ) : null}
                  </View>
                </TouchableOpacity>

Keep in mind, this id will be used to update the isSelected key in your friendList.

In the handlePress() we will compare the parameter id with the array's id and if it matches we will update the isSelected key to true otherwise we will keep the object as it is. Then, we will update our friendList.

 const handlePress = (selectedID) => {
    const updatedFriendList = friendList.map((val) =>
      val.id === selectedID ? { ...val, isSelected: true } : val
    );
    setFriendList(updatedFriendList);
  };

Here's how it will look in action.

Gist