lundi 15 novembre 2021

How select only one items in Flatlist?

I am trying to implement selecting only one user from a list of users. I am using Flatlist and ReactNativeBouncyCheckBox. I wrote a function which selects only one user and I update my state (data) but the list with the checkboxes is not updated. How can I make it possible to select only one user?

FlatList

        <FlatList
            extraData={selectedUser}
                data={data}
                renderItem={({item}, index) => (
                  <View style=>
                    <View>
                      <View style={styles.personalChat}>
                        <BouncyCheckbox
                          checked={true}
                          isChecked={item.isChecked}
                          iconStyle=
                          unfillColor="transparent"
                          fillColor="#2563EB"
                          onPress={() => selectedMembers(item.id)}
                        />
                        <Text> {item.isChecked}</Text>
                        <UserItem
                          imgSrc={item.imgUrl}
                          firstName={item.f_name}
                          surName={item.l_name}
                          location={item.location}
                        />
                      </View>
                    </View>
                  </View>
                )}
              />

selectedMembers

const [data, setData] = useState([
    {
      id: 1,
      imgUrl:
        'https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8dXNlcnxlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&w=1000&q=80',
      f_name: 'Wade',
      l_name: 'Warner',
      location: 'London',
      isChecked: false,
    },
    {
      id: 2,
      imgUrl: 'https://randomuser.me/api/portraits/men/7.jpg',
      f_name: 'Dmitriy',
      l_name: 'Kovalenko',
      location: 'Dubai',
      isChecked: false,
    },
    {
      id: 3,
      imgUrl: 'https://randomuser.me/api/portraits/men/15.jpg',
      f_name: 'Alex',
      l_name: 'Tunder',
      location: 'Dubai',
      isChecked: false,
    },
  ]);
      const selectedMembers = id => {
    let temp = data.map(data => {
      if (id === data.id) {
        return {...data, isChecked: !data.isChecked};
      }
      return data;
    });

    for (var i = 0; i < data.length; i++) {
      data[i].isChecked = false;
    }
    data.isChecked = true;

    console.log('t', temp);
    setData(temp);
  };



Aucun commentaire:

Enregistrer un commentaire