How can I disable multiple select in react map

Issue

This Content is from Stack Overflow. Question asked by Julia Schafer

When I click the white background button I just want to give yellow background to the selected/pressed button. but for now, I can select more than one button. how can I disable multiple selections?

enter image description here

Common > AddressButton.tsx

    const handlePress = () => {
        setAddressData(addressData);
        if (ratesData) setRatesData(null);
        if (selectedRate) setSelectedRate(null);
        setSelectedItem(!selectedItem)
    };

        const [selectedItem, setSelectedItem] = useState<boolean>(false);

    return (
        <HomeAddressContainer isSelected={selectedItem}>
            <Pressable onPress={handlePress}>
            <HomeAddressRow>
                <HomeAddressIcon>
                <SVGCustomIcon name={selectedItem ? "HomeAddressIcon" : "HomeIconWhite"} />
                    <HomeAddressTitle>{name}</HomeAddressTitle>
                    <HomeAddressName>{company}</HomeAddressName>
                    <HomeAddressStreet>{street1}</HomeAddressStreet>
                    <HomeAddressStreet>{city}, {zip}, {country}</HomeAddressStreet>
            
        </HomeAddressContainer>
    );
};

style.ts for AddressButton.tsx

interface HomeAddressProps {
    isSelected: boolean;
}

export const HomeAddressContainer = styled.View<HomeAddressProps>`
    width: 219px;
    height: 94px;
    border-radius: 8px;
    background-color: #ffffff;
    ${props => props.isSelected && 'background-color: #f9b300'};

`;

Components > Addresses.tsx

  const handlePress = (rate: any, index: number) => {
        setSelectedItem(index);
        // selectRate(rate);
        setSelectedRate(rate);
    };

{addressesList.map((address: AddressData, index) => (
                  <Pressable
                            key={index}
                            onPress={() => handlePress(address, index)}>
                <HomeAddress
                    key={index}
                    addressData={address}
                    packageId={packageId}
                    isSelected={index === selectedItem}
                />
                </Pressable>
            ))}



Solution

This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?