Mapbox-GL-JS – Making Map Ref Object Available on First Modal Window Render in Mapbox-GL-JS

arcgis-reactmapbox-gl-jsreact

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/

Best Answer

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)}