Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 309
Alex Avatar asked Apr 07 '26 15:04

Alex


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} />;
}
like image 148
yudhiesh Avatar answered Apr 10 '26 10:04

yudhiesh


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:

enter image description here

Learning References

Thanks!

like image 32
Dolly Avatar answered Apr 10 '26 11:04

Dolly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!