5

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;
Peter
  • 53
  • 1
  • 4
  • Can you show us your `this.props.onClick(data);` function ? I think it's because you have a setState somewhere. When you call the setState function, the component is rerendering, it could be the reason of your refresh – tinmarfrutos Aug 22 '18 at 13:14
  • Yes its in my parent class: `onChild2ButtonClick = (dataFromChild2) => { this.setState({ infoIndex: dataFromChild2 }); };` – Peter Aug 22 '18 at 13:57

1 Answers1

1

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

Vadim Gremyachev
  • 57,952
  • 20
  • 129
  • 193