I'm building a small App using ReactJS and Mapbox GL JS.
const MapRender = () => {
const mapContainerRef = useRef(null);
const map = new mapboxgl.Map({
container: mapContainerRef.current,
style: "mapbox://styles/mapbox/streets-v11",
center: [0, 0],
zoom: 1
});
map();
useEffect(()=>{
..........//Code
},[]);
return (
<div>
<div className="map-container" ref={mapContainerRef} />
</div>
);
};
export default MapRender;
My code above basiclly display a map on a webpage. But I got the error messenge:
Invalid type: 'container' must be a String or HTMLElement.
Everythings will be fine if I put const map = new mapboxgl.Map() into useEffect() but it's mean eachtime when I setState the Map will call and reload again.
I expect the use the same map during the whole runtime of my app.
How can I do that ?
If you do not want the map to be reinitialized again every single time there is new data being passed to it. You can do the following where, the map is created when the ref is connected to the container div and it will not create the map if it's already been created.
export default function MapRender() {
const ref = useRef(null);
const [map, setMap] = useState(null);
useEffect(() => {
if (ref.current && !map) {
const map = new mapboxgl.Map({
container: ref.current,
style: "mapbox://styles/mapbox/streets-v11",
center: [0, 0],
zoom: 1
});
setMap(map);
}
}, [ref, map]);
return <div className="map-container" ref={ref} />;
}
Use below format to remove TS Error:
const content = useRef<string | HTMLElement>(null);
Code where Mapbox gl Map Instance will be created once:
Stackblitz: https://stackblitz.com/edit/react-xnetjp?devtoolsheight=33&file=src/App.js
This is the TS Error as in mapbox-gl.d.ts(Declaration File) says that the container has to be a string or an HTML element.
Screenshot:

Learning References
Thanks!
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