Search code examples
reactjsreact-google-maps

react-google-maps is refreshing the map when onclick is performed


I'm trying to use react-google-maps as an latitude and longitude input in my app. In order to get the position that the user selected I'm using the onclick event and it works almost as expected because the marker is set, but the map is refreshing and going to the default center and zoom when the user selects the desired location. How can I avoid this weird behaviour?

import React from "react";
import { withScriptjs, withGoogleMap, GoogleMap, Marker, MarkerWithLabel } from "react-google-maps";

export default class MapTest extends React.Component {
    constructor(){
        super();
        this.state={
            isMarkerShown: false,
            markerPosition: null
        }
    }
    onMapClick= (e) => this.setState({
        markerPosition: e.latLng,
        isMarkerShown:true}
    );


  render() {
    var Map= withScriptjs(withGoogleMap((props) =>
    <GoogleMap
      defaultZoom={12}
      center={ { lat:  4.4360051, lng: -75.2076636 } }
      onClick={this.onMapClick}
      >
    {this.state.isMarkerShown && <Marker position={this.state.markerPosition} />}
        </GoogleMap>));
      return (<Map {...this.props} />);

  }
}

Solution

  • That is because you are creating a new object in each render call.

    the withScriptjs(withGoogleMap should be stored somewhere an re-used

    For example

    class MapTest extends React.Component {
      //...
    
      Map = withScriptjs(
        withGoogleMap(props => (
          <GoogleMap
            defaultZoom={12}
            center={{ lat: 4.4360051, lng: -75.2076636 }}
            onClick={props.onClick}
          >
            {props.children}
          </GoogleMap>
        ))
      );
    
      render() {
        return <this.Map {...this.props} onClick={this.onMapClick}>
          {this.state.isMarkerShown && (
            <Marker position={this.state.markerPosition} />
          )}
        </this.Map>;
      }
    }
    

    Demo at https://codesandbox.io/s/n05jm6j0jm