What is the best way to give each Marker of Google API a different `useState()`?

Viewed 28

Problem

I am using google map API, and show location of events ( posts ) on google map, but here is a problem:

When I click a marker to see <InfoWindowF/>, the other <InfoWindowF/>s also pops up as I use the same useState( ) and state variable for all <MarkerF/>. I want to give different useState( ) or possibily better way to make certain Infowindow to pop up when certain Marker is clicked. How can I do it?

Code

import React, { useState } from 'react'
import { GoogleMap, useLoadScript, InfoWindowF, MarkerF } from "@react-google-maps/api"

const API_KEY = "0123456789"

const latitude = 35.685661305110415
const longitude =139.75255896834707

export default function GoogleMapAPI({posts}:any) {

  const { isLoaded }: any = useLoadScript({
    googleMapsApiKey: API_KEY,
  })
  const [clicked, setClicked] = useState(false)
  const showInfoWin = (e: any) =>{
    setClicked(!clicked)
    
  }
  if(isLoaded)return(
    <>
     <div className='flex flex-col'>
       <GoogleMap
          zoom={11}
          center={{ lat: latitude, lng: longitude }}
       >
     {
       posts.slice(0, 30).map((post: any)=>(
        <>
          <MarkerF
            position={{lat: post.latitude, lng: post.longitude}}
            onClick={()=>setClicked(!clicked)}
          >
          {(clicked)?(
            <InfoWindowF
               onCloseClick={()=>setClicked(!clicked)}
            >
              <span>
              {post.title}
              </span>
           </InfoWindowF>):('')
          </MarkerF>
         </>
        ))}
      </GoogleMap>
     </div>
   </>
  )
}



1 Answers

Make a component for MarkerF and pass down props like: post={post}, then declare useState() inside of the component, this way marker has different states variables.

Related