Module 07 - Map Components: the Web Component API

Level 1 · Your First Maps · 🟢 Beginner · 3 hours · Prereq: Module 06


What you'll build

The Module 06 application rebuilt declaratively with <arcgis-map>, <arcgis-legend>, <arcgis-layer-list> and friends - roughly 60% less JavaScript. Then the hybrid pattern that real applications actually use: components for layout, the imperative API for logic.


Why this matters

@arcgis/map-components is Esri's current direction for UI. It is what the samples increasingly use, it is what makes framework integration bearable, and it is what this repository uses (<arcgis-scene> in JSX with an imperative sceneRef for everything else).

But it is not a replacement for the imperative API, and treating it as one leads to fighting the framework. Knowing exactly where the boundary sits is the point of this module.


Concepts

1. What a web component is

A custom HTML element the browser knows how to render, registered via customElements.define(). It has attributes (strings, in HTML), properties (any type, in JS), and events.

<arcgis-map basemap="arcgis/navigation" center="-76.481,44.231" zoom="13">
  <arcgis-zoom position="top-left"></arcgis-zoom>
  <arcgis-legend position="bottom-left"></arcgis-legend>
</arcgis-map>

That is a complete map. No JavaScript beyond registering the components.

Three things follow from "it's just HTML":

  • It works in any framework, or none
  • Attributes are strings; complex values must be set as properties in JS
  • Styling crosses a shadow boundary, which has consequences (see §7)

2. Registering components - two ways, and they differ a lot

Global registration - everything at once:

import { defineCustomElements } from "@arcgis/map-components/dist/loader";
defineCustomElements();

Simple, and what this repository currently does in src/main.jsx. The cost: it makes every component reachable from your entry module, so the bundler keeps them all. On a marketing homepage that never shows a map, you still ship the component library.

Per-component registration - the tree-shakeable path:

import "@arcgis/map-components/components/arcgis-map";
import "@arcgis/map-components/components/arcgis-legend";
import "@arcgis/map-components/components/arcgis-zoom";

Importing the module is the registration - each one self-registers on import. Only the components you name are bundled.

Use per-component imports. The exception is a large app where every route shows a map anyway, and even then, per-component is not worse. This repo's CLAUDE.md explicitly flags its global defineMapComponentsElements() as unfinished cleanup for exactly this reason.

You also need the components' stylesheet:

import "@arcgis/map-components/main.css";

3. Attributes vs properties

<!-- attribute: always a string, parsed by the component -->
<arcgis-map basemap="arcgis/navigation" zoom="13"></arcgis-map>
// property: any JS value
const el = document.querySelector("arcgis-map");
el.map = myMapInstance;             // a Map object - impossible as an attribute
el.center = [-76.481, 44.231];      // an array
el.constraints = { minZoom: 10 };   // an object

Rule: primitives can be attributes; objects, arrays and class instances must be properties.

In React 19 this distinction mostly disappears - React 19 sets non-string props as properties on custom elements automatically. In React 18 and earlier you needed a ref. If you see older tutorials doing ref.current.center = … for arrays, that's why.

4. The arcgisViewReadyChange event

The component creates the view asynchronously, just like new MapView().

const el = document.querySelector("arcgis-map");

el.addEventListener("arcgisViewReadyChange", () => {
  const view = el.view;              // the real MapView instance
  console.log("ready", view.spatialReference.wkid);
});

el.view is null until then. This is the same lifecycle wall as Module 05, wearing a different hat.

The components also expose el.ready (boolean) and re-emit the view's own events with an arcgis prefix - arcgisViewClick, arcgisViewChange, and so on.

5. Slotting and positioning

Child components position themselves inside the map through a position attribute:

<arcgis-map basemap="arcgis/navigation" center="-76.481,44.231" zoom="13">
  <arcgis-zoom position="top-left"></arcgis-zoom>
  <arcgis-search position="top-right"></arcgis-search>
  <arcgis-legend position="bottom-left"></arcgis-legend>
  <arcgis-scale-bar position="bottom-right" unit="metric"></arcgis-scale-bar>
</arcgis-map>

The component finds its parent map, gets the view, and calls view.ui.add(widget, position) for you.

This nesting is not optional. A widget component placed outside the map element has no view to attach to and renders nothing. In this repository's CLAUDE.md it is recorded as a rule: "Nav controls slotted inside <arcgis-scene> - otherwise no view connection." That was a real debugging session.

If you need a widget rendered outside the map (in your own sidebar), pass the view explicitly:

<arcgis-map id="theMap" ...></arcgis-map>
<aside>
  <arcgis-legend id="sideLegend"></arcgis-legend>
</aside>
mapEl.addEventListener("arcgisViewReadyChange", () => {
  document.getElementById("sideLegend").view = mapEl.view;
});

6. The component catalogue

There are 100+. The ones you will actually use:

Views: arcgis-map, arcgis-scene Navigation: arcgis-zoom, arcgis-home, arcgis-compass, arcgis-locate, arcgis-navigation-toggle, arcgis-fullscreen, arcgis-directional-pad Content: arcgis-legend, arcgis-layer-list, arcgis-basemap-gallery, arcgis-basemap-layer-list, arcgis-basemap-toggle, arcgis-bookmarks, arcgis-table-list Search/data: arcgis-search, arcgis-feature-table, arcgis-features, arcgis-feature-form Measure: arcgis-measurement, arcgis-area-measurement-2d, arcgis-distance-measurement-2d, arcgis-direct-line-measurement-3d, arcgis-area-measurement-3d, arcgis-volume-measurement 3D: arcgis-daylight, arcgis-weather, arcgis-shadow-cast, arcgis-line-of-sight, arcgis-slice, arcgis-elevation-profile, arcgis-building-explorer Editing: arcgis-sketch, arcgis-editor, arcgis-snapping-controls Time: arcgis-time-slider, arcgis-time-of-day-slider Layout: arcgis-expand, arcgis-placement, arcgis-swipe

Full list: https://developers.arcgis.com/javascript/latest/components/

7. Styling and the shadow DOM

Components render into a shadow root. Your page CSS cannot select inside it:

/* ❌ does nothing - .esri-legend is inside the shadow root */
arcgis-legend .esri-legend__service { font-weight: bold; }

Three things that do work:

/* 1. Style the host element itself */
arcgis-legend { --calcite-color-text-1: #eee; max-height: 300px; }

/* 2. CSS custom properties DO inherit through shadow boundaries */
:root { --calcite-color-brand: #0066ff; }

/* 3. ::part(), where the component exposes parts */
arcgis-legend::part(container) { border-radius: 12px; }

Custom properties inherit; selectors don't. That is the rule, and it is why Calcite tokens are the sanctioned theming route.

The catch that gets people: inheritance works, but only if the property is set on an ancestor of the host in the light DOM. If a widget is rendered into a shadow root of another shadow root - which some SDK widgets do internally - an inherited property can still fail to land. That is when you inject from JS onto the shadow host, as this repository does for Calcite tokens in WebSceneViewer.jsx.


Build it

Step 1 - Pure declarative

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no" />
  <title>Map Components</title>
</head>
<body>
  <arcgis-map
    id="map"
    basemap="arcgis/navigation"
    center="-76.481,44.231"
    zoom="13"
  >
    <arcgis-zoom position="top-left"></arcgis-zoom>
    <arcgis-search position="top-right"></arcgis-search>

    <arcgis-expand position="top-right" group="tools">
      <arcgis-layer-list></arcgis-layer-list>
    </arcgis-expand>

    <arcgis-expand position="top-right" group="tools">
      <arcgis-legend></arcgis-legend>
    </arcgis-expand>

    <arcgis-expand position="top-right" group="tools">
      <arcgis-basemap-gallery></arcgis-basemap-gallery>
    </arcgis-expand>

    <arcgis-scale-bar position="bottom-left" unit="metric"></arcgis-scale-bar>
    <arcgis-fullscreen position="bottom-right"></arcgis-fullscreen>
  </arcgis-map>

  <script type="module" src="/src/main.js"></script>
</body>
</html>

src/main.js:

import "./style.css";

import esriConfig from "@arcgis/core/config.js";
import FeatureLayer from "@arcgis/core/layers/FeatureLayer.js";

// Per-component imports - each registers itself and only these are bundled
import "@arcgis/map-components/components/arcgis-map";
import "@arcgis/map-components/components/arcgis-zoom";
import "@arcgis/map-components/components/arcgis-search";
import "@arcgis/map-components/components/arcgis-expand";
import "@arcgis/map-components/components/arcgis-layer-list";
import "@arcgis/map-components/components/arcgis-legend";
import "@arcgis/map-components/components/arcgis-basemap-gallery";
import "@arcgis/map-components/components/arcgis-scale-bar";
import "@arcgis/map-components/components/arcgis-fullscreen";

esriConfig.apiKey = import.meta.env.VITE_ARCGIS_API_KEY;

const mapEl = document.getElementById("map");

mapEl.addEventListener("arcgisViewReadyChange", () => {
  const view = mapEl.view;

  // The component made the Map for us; we add operational layers to it.
  view.map.add(
    new FeatureLayer({
      url: "https://services.arcgis.com/P3ePLMYs2RVChkJx/arcgis/rest/services/USA_Major_Cities/FeatureServer/0",
      title: "US Major Cities",
      outFields: ["NAME", "POPULATION", "ST"],
      popupTemplate: {
        title: "{NAME}, {ST}",
        content: "Population: {POPULATION}",
      },
    })
  );
});

style.css:

@import "@arcgis/core/assets/esri/themes/light/main.css";
@import "@arcgis/map-components/main.css";

html, body { margin: 0; padding: 0; height: 100%; }
arcgis-map { display: block; height: 100vh; }

Note arcgis-map { display: block; height: 100vh; }. Custom elements are display: inline by default, which gives them no height - the same 0-height failure as Module 03, wearing a different hat.

Compare this to Module 06. Everything except the FeatureLayer is now markup. For a straightforward map viewer, this is unambiguously the better code.

Step 2 - Reach the imperative API when you need it

The declarative surface covers configuration. It does not cover logic. Anything conditional, computed or interactive still needs the view.

mapEl.addEventListener("arcgisViewReadyChange", async () => {
  const view = mapEl.view;

  const cities = new FeatureLayer({ url: CITIES_URL, outFields: ["*"] });
  view.map.add(cities);

  // Wait for the LayerView - needed for anything view-specific
  const layerView = await view.whenLayerView(cities);

  // Highlight on hover
  let highlightHandle = null;
  view.on("pointer-move", async (event) => {
    const { results } = await view.hitTest(event, { include: cities });
    highlightHandle?.remove();
    highlightHandle = results.length
      ? layerView.highlight(results[0].graphic)
      : null;
  });
});

This is the boundary. Attributes for what the map is; JavaScript for what it does.

Step 3 - Set object properties from JS

mapEl.center = [-79.383, 43.653];        // array - property, not attribute
mapEl.constraints = { minZoom: 8, maxZoom: 18 };
mapEl.popupDisabled = true;

Try it as an attribute and watch it fail:

<!-- ❌ the component receives the literal string "[object Object]" -->
<arcgis-map constraints="{minZoom: 8}"></arcgis-map>

Step 4 - Listen to re-emitted events

mapEl.addEventListener("arcgisViewClick", (event) => {
  const { mapPoint } = event.detail;
  console.log(mapPoint.longitude, mapPoint.latitude);
});

mapEl.addEventListener("arcgisViewChange", () => {
  console.log("zoom:", mapEl.zoom);
});

Note event.detail. Web components carry payloads in CustomEvent.detail, so the SDK's event object is one level down. Forgetting this gives you undefined and no error.

Step 5 - Widgets outside the map

<div class="layout">
  <aside id="sidebar">
    <h2>Layers</h2>
    <arcgis-layer-list id="sideLayers"></arcgis-layer-list>
    <h2>Legend</h2>
    <arcgis-legend id="sideLegend"></arcgis-legend>
  </aside>
  <arcgis-map id="map" basemap="arcgis/light-gray" center="-76.481,44.231" zoom="12"></arcgis-map>
</div>
.layout { display: grid; grid-template-columns: 300px 1fr; height: 100vh; }
#sidebar { overflow: auto; padding: 16px; border-right: 1px solid #e5e7eb; }
arcgis-map { display: block; height: 100%; }
mapEl.addEventListener("arcgisViewReadyChange", () => {
  const view = mapEl.view;
  document.getElementById("sideLayers").view = view;
  document.getElementById("sideLegend").view = view;
  // Account for the sidebar so goTo centres in the visible area
  view.padding = { left: 0 };   // grid layout means the map div already excludes it
});

Why the components need view set explicitly here: they look for a parent arcgis-map to attach to. Outside that tree there is nothing to find, so you supply it.

Step 6 - Compare the bundles

Build both versions (Module 06's imperative and this one) and compare gzipped JS size.

Then swap the per-component imports for the global loader:

import { defineCustomElements } from "@arcgis/map-components/dist/loader";
defineCustomElements();

Rebuild. Record the difference. This is the concrete cost of global registration and the number to quote when someone asks why it matters.


How it works

What the component does on connect

  1. connectedCallback fires when the element enters the DOM
  2. It reads its attributes and reflects them to properties
  3. <arcgis-map> constructs a Map (or uses itemId to construct a WebMap) and a MapView pointed at its own internal container div
  4. Child widget components walk up the DOM for an arcgis-map/arcgis-scene ancestor
  5. When the view is ready, each child constructs its widget and calls view.ui.add()
  6. The map element dispatches arcgisViewReadyChange

Step 4 is why nesting is required. Step 6 is why el.view is null before it.

Why 5.x components are Lit-based

Look inside node_modules/@arcgis/map-components/dist/components/arcgis-map/customElement.js and you will find imports from lit and @arcgis/lumina. Esri moved the components onto Lit (via their Lumina layer) in 5.x, having previously used Stencil.

Practical consequences:

  • Components are real ES modules that self-register on import - no build-time codegen step
  • Per-component imports work cleanly, which is why §2's advice is possible
  • Properties are reactive in the Lit sense; setting one schedules a re-render

Components vs the imperative API - the actual decision

Use components for Use the imperative API for
The view container Adding/removing layers dynamically
Standard widgets in standard positions Querying, filtering, analysis
Anything a designer might want to move hitTest, highlight, custom interaction
Framework templates (JSX, Vue SFC) Everything with conditional logic
Declarative config from a CMS/DB Anything you need a handle to for cleanup

They compose. <arcgis-map> gives you el.view, and from there the entire imperative API is available. There is no wall. This repository is a good worked example: <arcgis-scene> in JSX for the container and nav widgets, sceneRef.current.view for every tool.


Common mistakes

Forgetting display: block and a height on the custom element. Custom elements are inline by default. 0-height map, no error.

Passing objects as attributes. Attributes stringify. Set properties in JS.

Reading el.view synchronously after page load. It's null until arcgisViewReadyChange.

Putting widget components outside the map element. No parent view to attach to. Either nest them, or set .view yourself.

Trying to style widget internals with descendant selectors. Shadow DOM. Use custom properties or ::part().

Using defineCustomElements() in an app that shows a map on one route. You just made every route pay for the whole component library.

Forgetting event.detail. arcgisViewClick carries the SDK event object in detail, not on the event itself.


Exercises

Exercise 07.1 - Rebuild Module 05 declaratively

Take your camera control panel from Module 05 and rebuild it with components. Use arcgis-bookmarks for the bookmarks instead of your hand-rolled buttons.

Then answer honestly: which parts were better declarative, and which parts did you have to drop back to JavaScript for? Write three bullet points. This is the judgement the module is teaching.

Exercise 07.2 - WebMap by id

Replace the basemap/center/zoom attributes with a single item-id attribute pointing at a public WebMap (ids in RESOURCES.md).

Observe:

  • The layers, symbology and popups all arrive configured
  • The initial extent comes from the item, so center/zoom are ignored
  • arcgis-legend populates itself with no extra work

Then explain, in two sentences, why this is the architecture of this repository's viewer.

Exercise 07.3 - Theme the components

Build a light/dark toggle that themes both your own UI and the ArcGIS components.

Requirements:

  • Use Calcite custom properties, not descendant selectors
  • Verify it reaches arcgis-legend, arcgis-layer-list and arcgis-search
  • Find at least one thing it does not reach, and write down what you'd do about it

Exercise 07.4 - Measure the registration cost

Produce a small table:

Registration approach Components used gzipped JS
defineCustomElements() 9
per-component imports 9
per-component imports 3

Then state the rule you'd put in a team style guide, in one sentence.


Checkpoint

  1. Why must widget components be nested inside <arcgis-map> (unless you do something else)?
  2. When is el.view available?
  3. Why can't you pass constraints as an HTML attribute?
  4. Name two ways to style inside a component's shadow DOM, and one that doesn't work.
  5. What's the cost of defineCustomElements() versus per-component imports?
  6. Give one thing components do better than the imperative API, and one thing they can't do at all.
  1. A child widget component finds its view by walking up the DOM for an arcgis-map / arcgis-scene ancestor. Outside that tree it has no view and renders nothing - unless you set .view on it manually.
  2. After the arcgisViewReadyChange event fires (or when el.ready is true). It's null before that.
  3. Attributes are strings. An object attribute stringifies to [object Object]. Set it as a property in JS.
  4. Works: CSS custom properties (they inherit through shadow boundaries), and ::part() where exposed. Doesn't work: descendant selectors targeting internal classes.
  5. Global registration makes every component reachable from your entry module, so the bundler keeps them all - typically hundreds of KB you don't use.
  6. Better: declarative configuration and layout, especially in framework templates and config-driven apps. Can't do: anything conditional or computed - dynamic layer management, queries, hitTest, custom interaction, cleanup-sensitive handles.

Further reading


Level 1 complete. Take the L1 challenge, then start Module 08 - FeatureLayer: the Workhorse.