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;
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With