Ilya Grushevskiy
Ilya Grushevskiy

Reputation: 141

In react, trouble passing onClick from Marker in Google Maps to app.js

I want to note the onClick event when the marker is clicked and pass it up to App.js. The map is loading and the code runs, but all I get when I click on a marker is the onClick console.log in my Map.js returning an empty object.

Child component:

function MyComponent( places, onMarkerClickMap ) {

  let allTheMarkers = 
    .
    .
    .
  })

  let markerClick = onMarkerClickMap;

  let foundMarkers = places.foundPlaces.map(place => {

    return (
        <Marker
            key={place.id}
            position={{ lat: place.lat, lng: place.lng }} 
            icon={place.alive ? icon1 : iconDead}
            onClick={() => {console.log(markerClick)}}
        />
    );
  })

  return (
    <LoadScript
      googleMapsApiKey={API}
    >
      <GoogleMap
        mapContainerStyle={containerStyle}
        center={center}
        zoom={11.3}
        options={{styles: mapStyles}}
      >
        
        {foundMarkers ? foundMarkers : allTheMarkers}

      </GoogleMap>

    </LoadScript>
  )
}

Parent component:

handleMarkerClick = (e) => {
      const id = e.target;
      console.log(id);
  }

  render() {
    return (
      <div className="container">
        <div className="wrapper">
          <Map
            places={this.state.places}
            foundPlaces={this.state.foundPlaces}
            onMarkerClickMap={this.handleMarkerClick}
          />
        </div>
      </div>
    );
  }

Upvotes: 1

Views: 611

Answers (2)

AGrush
AGrush

Reputation: 1167

not sure console logging a whole function is gonna give you anything useful..

if you do this does it console log the id? onClick={() => {markerClick()}}

cos markerClick is essentially the handleMarkerClick function

Upvotes: 1

Patrik Braborec
Patrik Braborec

Reputation: 34

You do not call markerClick. I think you should do something like:

<Marker
    key={place.id}
    position={{ lat: place.lat, lng: place.lng }} 
    icon={place.alive ? icon1 : iconDead}
    onClick={() => markerClick()}
/>

Upvotes: 1

Related Questions