Search code examples
reactjsonclickinfowindowuse-state

Display InfoWindow only when marker clicked in reactJS


I want to show infoWindow only when clicked.

I am using useState to update value in order to check if marker is clicked to show InfoWindow else don't show InfoWindow.

my code:

import React, { useState } from "react";
import {
  GoogleMap,
  useLoadScript,
  Marker,
  InfoWindow,
} from "@react-google-maps/api";
import "./App.css";
import mapStyles from "./mapStyles";

const mapContainerStyle = {
  width: "100%",
  height: "100vh",
};
const center = {
  lat: 51.103807,
  lng: 10.057477,
};

const options = {
  styles: mapStyles,
  mapTypeControl: false,
  fullscreenControl: false,
  streetViewControl: false,
};


export default function App() {
  const [setSState, sstate] = React.useState(null);

  const { isLoaded, loadError } = useLoadScript({
    googleMapsApiKey: process.env.REACT_APP_GOOGLE_KEY,
    libraries,
  });

  if (loadError) return "error loading maps";
  if (!isLoaded) return "loading maps";

  return (
    <div>
      <h1>Find a dealer near you</h1>
      <GoogleMap
        mapContainerStyle={mapContainerStyle}
        zoom={6}
        center={{ lat: 50.985509, lng: 10.690508 }}
        options={options}
      >
        <Marker
          position={{ lat: 50.985509, lng: 10.690508 }}
          onClick={() => {
            sstate(center);
            console.log("marker clicked");
          }}
        ></Marker>
        { sstate[0] ?  (
        <InfoWindow
          position={{
            lat: 51.081753,
            lng: 13.696073,
          }}
        >
          <div>
            <h3>Some text</h3>
            <h4>Some text</h4>
            <p>Some text</p>
          </div>
        </InfoWindow>
        ): null}
      </GoogleMap>
    </div>
  );
}

When I click the marker InfoWindow doesn't show up. What am I not doing and should do? Is there a different, simple way?


Solution

  • It looks like you have confused the current state value and a function that lets you update it in the Marker handler. You also assign center object to state which doesn't have center[0] property which you use in your render condition.

    Try to replace const [setSState, sstate] = React.useState(null); with const [marker, setMarker] = React.useState(null); to make things clear.

    Change onClick in Marker to

    onClick={() => {
      setMarker(center);
      console.log("marker clicked");
    }}
    

    And place where you render InfoWindow to

    { marker ? (
      <InfoWindow
        position={{
          lat: 51.081753,
          lng: 13.696073,
        }}
      >
        <div>
          <h3>Some text</h3>
          <h4>Some text</h4>
          <p>Some text</p>
        </div>
      </InfoWindow>
    ) : null }