react-mapbox-gl
react-mapbox-gl copied to clipboard
clicking on popup re-renders the whole map?!
Also, for me the demo codes are a bit hard to understand. It would have helped more if they were written to accommodate React style. code:
import React, { useState } from "react";
import ReactMapboxGl, { Layer, Feature, Popup } from "react-mapbox-gl";
function Map(props) {
const Map = ReactMapboxGl({
accessToken: process.env.REACT_APP_MAPBOX_API_KEY,
});
const [showPopUp, setShowPopUp] = useState(false);
console.log(props.longitude);
const { data } = props;
return (
<Map
style="mapbox://styles/aasutossh/ckacm4rvi3khl1inmsvf6fjq9"
containerStyle={{
height: "100vh",
width: "100vw",
}}
center={[data.lng, data.lat]}
zoom={[15]}
>
<Layer
type="circle"
id="marker"
paint={{
"circle-color": "#ff5200",
"circle-stroke-width": 1,
"circle-stroke-color": "#fff",
"circle-stroke-opacity": 1,
}}
>
<Feature
coordinates={[data.lng, data.lat]}
onClick={() => setShowPopUp(true)}
/>
</Layer>
{showPopUp && (
<Popup
coordinates={[data.lng, data.lat]}
offset={{
"bottom-left": [12, -38],
"bottom": [0, -38],
"bottom-right": [-12, -38],
}}
>
<h1>Popup</h1>
</Popup>
)}
</Map>
);
}
export default Map;
same issue for all events onMouseEnter, onMouseLeave... we need state to modify popup coordinate but every time the useState call, it trigger a re-render for Features
Any solutions?
@whitexgate @Gondolav one solution would be to move this:
const Map = ReactMapboxGl({
accessToken: process.env.REACT_APP_MAPBOX_API_KEY,
});
Outside the Map function.
import React, { useState } from "react";
import ReactMapboxGl, { Layer, Feature, Popup } from "react-mapbox-gl";
const Map = ReactMapboxGl({
accessToken: process.env.REACT_APP_MAPBOX_API_KEY,
});
function MapWrapper(props) {
const [showPopUp, setShowPopUp] = useState(false);
console.log(props.longitude);
const { data } = props;
return (
<Map
style="mapbox://styles/aasutossh/ckacm4rvi3khl1inmsvf6fjq9"
containerStyle={{
height: "100vh",
width: "100vw",
}}
center={[data.lng, data.lat]}
zoom={[15]}
>
<Layer
type="circle"
id="marker"
paint={{
"circle-color": "#ff5200",
"circle-stroke-width": 1,
"circle-stroke-color": "#fff",
"circle-stroke-opacity": 1,
}}
>
<Feature
coordinates={[data.lng, data.lat]}
onClick={() => setShowPopUp(true)}
/>
</Layer>
{showPopUp && (
<Popup
coordinates={[data.lng, data.lat]}
offset={{
"bottom-left": [12, -38],
"bottom": [0, -38],
"bottom-right": [-12, -38],
}}
>
<h1>Popup</h1>
</Popup>
)}
</Map>
);
}
export default MapWrapper;
A memoized ReactMapboxGl function would be the ultimate fix but seems this isn't provided by react-mapbox-gl yet