0

I have a table where when I click on a row of the table, I get the content/objects of the row which I am passing to the Dialog component that uses

react-map-gl

to display the item's location based on the xy coordinate.

  const mapRef = useRef(null);

// makeshift data
  const rowData = {
    laty: 5.4959,
    longx: 7.0807,
  };

  useEffect(() => {
    console.log(mapRef.current); // does not render the map methods/objects on first modal render
    if (mapRef.current) {
      mapRef.current?.setCenter({
        lat: rowData?.laty,
        lng: rowData?.longx,
      });
    }
  }, [rowData]);

When clicked it shows the map, but the issue is that the mapref returns null on the first render, when I console.log(mapref) shows null instead of the available mapref objects which I can use such as flyTo(), setCenter() etc. I know it's supposed to show null on the initial render but not when I launch the Modal.

how can I solve this?

Please see sandbox for better context

https://xbzi8r.csb.app/

3 Answers 3

2

Solved it, used useState instead of useRef, and it solved it.

const [map, setMap] = useState(null);

useEffect(() => {
    if (dss_rowData && map) {
      map?.setCenter({
        lat: Number(laty),
        lng: Number(longx),
      });
    }
  }, [rowData, map]);

ref={(ref) => setMap(ref)}
0

...just as a little extra clarification for anyone else having the same issue:

<Map
    ref={(ref) => setMap(ref)}
    // ... other Map props ...
>
0

Although using setMap gets you the map, I often couldn't use this map, because it was not fully loaded, I got an error:

 Uncaught Error: Style is not done loading

In my case, it was better to wait for the map to load. I was using React, MapLibre (Mapbox fork) and wanted to add terrain:

  const onMapLoad = useCallback((e: MapLibreEvent) => {
    const map = e.target;
    // Setting up terrain like this is easier than having my own styles.json file/configuration
    const terrainSourceId = "terrain";
    map.addSource(terrainSourceId, {
      type: "raster-dem",
      url: `https://api.maptiler.com/tiles/terrain-rgb/tiles.json?key=${mapTilerKey}`
    });
    map.setTerrain({
      source: terrainSourceId
    });
    map.on("contextmenu", () => {
      console.log("contextmenu clicked");
    });
  }, []);

...

<Map
  onLoad={onMapLoad}
  ...
/>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.