next.jsmapbox-gl

mapbox-gl error TypeError: Cannot read property 'createElement' of undefined using Nextjs V13+ app router


mapbox-gl-js version: "mapbox-gl": "^2.15.0",

browser: Chrome

Reproducible example: https://codesandbox.io/p/sandbox/small-sun-htxpr2

I'm using the regular version of mapbox-gl in a nextjs application. The map renders perfectly however this run-time error shows up in the terminal and prevents from building successfully.

- error node_modules\mapbox-gl\dist\mapbox-gl.js (31:21756) @ Object.resolveURL
- error TypeError: Cannot read property 'createElement' of undefined

Any thoughts on how to fix it?

app/components/Map.js

"use client";

// React
import React, { useRef, useEffect, useState } from "react";
// Mapbox
import mapboxgl from "mapbox-gl"; // eslint-disable-line import/no-webpack-loader-syntax
import MapboxLanguage from '@mapbox/mapbox-gl-language';

mapboxgl.setRTLTextPlugin('https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-rtl-text/v0.2.3/mapbox-gl-rtl-text.js');
const Map = () => {
  const mapContainer = useRef(null);
  const map = useRef(null);
  const [lng, setLng] = useState(35.90719);
  const [lat, setLat] = useState(31.97182);
  const [zoom, setZoom] = useState(11.5);
  const [mapIsLoaded, setMapIsLoaded] = useState(false);

  // Used for intitializing map
  useEffect(() => {
    if (map.current) return; // initialize map only once

    map.current = new mapboxgl.Map({
      container: mapContainer.current,
      style: "mapbox://styles/mapbox/streets-v11",
      center: [lng, lat],
      zoom: zoom,
      hash: true,
      // bounds:[]
    });

    map.current.on("load", () => {
      setMapIsLoaded(true);
    });
    // Clean up on unmount
    return () => map.current.remove();
  }, []);

  return (
    <div ref={mapContainer} style={{ minHeight: "100vh", minWidth: "100vw" }} />
  );
};

export default Map;

Solution

  • // mapboxgl.setRTLTextPlugin('https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-rtl-text/v0.2.3/mapbox-gl-rtl-text.js');
    

    This run time error wasn't because of the mapbox-gl library but becasue I was using @mapbox/mapbox-gl-language package to support arabic.

    I was directly using setRTLTextPlugin in the body of the function. Instead just add it inside the useEffect hook.