reactjsarcgisarcgis-js-api

How to access arcgis map via components?


The code below is taken directly from arcgis via react on how to display a map.

If i wanted to say, zoom in to a set of coordinates, but the code for that was set in another component, how can i get that component to talk to the map here in this component?

import Map from '@arcgis/core/Map';
import MapView from '@arcgis/core/views/MapView';

const map = new Map({
  basemap: "topo-vector"
});

const view = new MapView({
  container: "viewDiv",
  map: map
});

Solution

  • I resolved this by using redux toolkit to set the map as a global state object.

    1. The entire map view is set in a useEffect, once i initialize each of the views, i dispatch the map view to a reducer in rtk.
        dispatch(updateMapViewState(view));
    
        updateMapViewState: (state, action) => {
          state.view = action.payload
        },
    

    Then, when i want to use the map in a separate component, i do:

        const view = useSelector((state) => state.MapSlice.view);
    

    In this way, all components can access the map outside of the useEffect in the map component, and can manipulate it without creating a new map view. This worked for me. I assume you could probably do this with context api, but we aren't using that as a global state manager.