I am using mapbox-gl": "^2.10.0" and "react": "^18.2.0". I have a simple code in my component like so
import React, { useRef, useEffect } from 'react';
import mapboxgl from 'mapbox-gl';
function Map() {
const mapContainer = useRef(null);
const map = useRef(null);
useEffect(() => {
mapboxgl.accessToken = 'abc'; // replace with your own access token
if (map.current) return; // initialize map only once
map.current = new mapboxgl.Map({
container: mapContainer.current,
style: 'mapbox://styles/mapbox/streets-v11',
center: [-74.5, 40],
zoom: 9
});
// return () => map.current.remove(); // clean up on unmount
}, []); // empty dependencies array to run useEffect only on mount
return (
<div ref={mapContainer} style={{ width: '600px', height: '600px' }} />
);
}
export default Map;
If I uncomment the // return () => map.current.remove(); // clean up on unmount
line , map do not show on page.
Seems like having componentWillUnmount causes mapbox gl js not to render.
I dont know what to make of this and how to fix it? Any ideas?
Thanks