Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

My google map refreshes every time when I click on a marker

So when i click on a marker the map always refreshes, how can I prevent it? On clicking a marker will render specific infos about that marker, but its always realoading and goes back to its defaultCenter.

import React, { Component } from "react";
import { withGoogleMap, GoogleMap, Marker } from "react-google-maps";
import maplayout from "./mapstyle.js";


class Map extends Component {
  state = { users: []};

  onClick = (data) => {
    this.props.onClick(data);
  };

  render() {
  const GoogleMapExample = withGoogleMap(props => (
      <GoogleMap
        defaultCenter={{ lat: 47.507589, lng: 19.066128 }}
        defaultZoom={13}
      >
        {this.props.users.map((element, index) => (
          <Marker
            key = {index}
            icon={require("../assets/seenpinkek.svg")}
            position={{ lat: element.latitude, lng: element.longitude }}
            onClick={() => this.onClick(index)}
          />
        ))}
      </GoogleMap>
    ));
    return (
      <div>
        <GoogleMapExample
          containerElement={<div className="mapCont" />}
          mapElement={<div className="map" />}
          disableDefaultUI={true}
          isMarkerShown
          onClick={this.onClick}>
        </GoogleMapExample>
        </div>
    );
  }
}

export default Map;
like image 795
Peter Avatar asked Nov 07 '22 03:11

Peter


1 Answers

This is the expected behavior since parent component state is getting updated. To prevent your map component from re-rendering, you could let React know (via shouldComponentUpdate method) whether a component should be affected by change in state or props or not:

shouldComponentUpdate(nextProps) {
  // If shouldComponentUpdate returns false, 
  // then render() will be completely skipped until the next state change.
  // In addition, componentWillUpdate and componentDidUpdate will not be called. 
  return false;
}

or (to allow update when the data has actually changed):

shouldComponentUpdate(nextProps,nextState) {
    return (this.state.users !== nextState.users);
}

Demo

The similar issue with a solution has been reported here

like image 84
Vadim Gremyachev Avatar answered Dec 06 '22 14:12

Vadim Gremyachev