ReactJS Mapbox-gl Invalid type: 'container' must be a String or HTMLElement

Viewed 962

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 ?

2 Answers

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} />;
}
Related