Toggle an array item in react native?

This is basically a map that has building icons and when you tap on a building, it shows information for that building. I am struggling with logic for toggling individual items(buldings) in my array. Like only displaying building 1 for example. So when I tap on a Marker it should show the correct building in the array. I am showing partial code for mapscreen.js but will share all if needed.

Buildings.js

export const buildings = [
  {
    name: "Building1",
    description: "This is some information",
    xp: 25,
  },
  {
    name: "Building2",
    description: "This is some information.",
    xp: 25,
  },
];

Mapscreen.js

const [visible, setVisible] = useState(false);

//MAP THROUGH ARRAY, PASS ARRAY ITEMS AS PROPS TO OVERLAY COMPONENT 

const myBuilding = buildings.map((building, i) => (
    <OverlayBox key={i} title={building.name} info={building.description} xp={building.xp} />
  ));
  const toggleOverlay = () => {
    setVisible(!visible);
  };

return (
    <View>
      <Overlay isVisible={visible} onBackdropPress={toggleOverlay}>
        {myBuilding}**<--------DISPLAYS BOTH BUILDINGS RIGHT NOW**
      </Overlay>

      <Marker
          onPress={toggleOverlay}**<--------WANT TO DISPLAY BUILDING 1**
          coordinate={{ latitude: 34.0198536, longitude: -80.923467 }}
          title={"Building1"}
          description={"25 XP"}
        />
      <Marker
          onPress={toggleOverlay}**<--------WANT TO DISPLAY BUILDING 2**
          coordinate={{ latitude: 34.0195536, longitude: -80.924467 }}
          title={"Building2"}
          description={"25 XP"}
        />
</View>


Answer

Your approach is a bit weird

I suggest you:

  1. Make only one OverlayBox

  2. Pass to toggleOverlay the index of your building like

    <Marker onPress={() => toggleOverlay(0)}

  3. Set the visible building index in state like

    const toggleOverlay = (index) => { setVisibleBuilding(index); … };

  4. And pass the building to your OverlayBox like

    <OverlayBox building={buildings[visibleBuildingIndex]} … />