Reputation: 744
I have the following simple React Component using the react-mapbox-gl wrapper. So far, it's great, however I find a small annoyance when trying to update state, using the useState hook.
function Location(props) {
const [selectedMarker, setSelectedMarker] = useState(null);
const [markerBlock, setMarkerBlock] = useState(false)
const {payload} = useContext(MarkerContext);
const [latlong, setLatlong] = useState(null);
console.log(payload);
const Map = ReactMapboxGl({
accessToken:
'tokenHiddenforstackoverflow',
});
const getLatlng = (map, event) => {
setLatlong(event.lngLat);
}
return (
<>
<Map
style="mapbox://styles/mapbox/satellite-streets-v9"
containerStyle={{
height: '100vh',
width: '100%'
}}
onClick={getLatlng}
center={[18.432723671572944, -33.926210020024826]}
>
<ZoomControl />
</Map>
</>
);
}
export default Location;
Whenever I update the LatLong state, the mapbox background turns black and the whole map reloads. Not sure if a coding / structural error or a bug from Mapbox. I tried restructuring this into smaller components as well, but no difference.
Any ideas?
Upvotes: 4
Views: 4245
Reputation: 59358
This is expected behavior since with every state change, ReactMapboxGl
gets re-created. One solution (to prevent map API reload and maps re-render) would be to create a single instance of ReactMapboxGl
outside of Location
function:
//create a single instance of WebGl Mapbox map
const Map = ReactMapboxGl({
accessToken:
"--your token goes here--"
});
function Location(props) {
const [position, setPosition] = useState(null);
const handleClick = (map, event) => {
setPosition([event.lngLat.lat, event.lngLat.lng]);
};
return (
<Map
style="mapbox://styles/mapbox/satellite-streets-v9"
containerStyle={{
height: "100vh",
width: "100%"
}}
onClick={handleClick}
center={[18.432723671572944, -33.926210020024826]}
></Map>
);
}
export default Location;
Upvotes: 12