Module 11 - Popups That Don't Embarrass You

Level 2 · Layers & Data · 🟡 · 4 hours · Prereq: Module 10


What you'll build

A property-information popup with a title, a formatted attribute table, a chart, an image, a related-features list, a computed field, and a custom action button - then the same information rendered in your own React-free side panel instead, because sometimes a popup is the wrong container.


Why this matters

The popup is where users actually read your data. It is also the single most neglected part of most map applications - raw field names, unformatted numbers, null displayed as the word "null", dates as epoch integers, and a scrollbar inside a scrollbar.

Getting it right is cheap and it is what makes an app feel finished.


Concepts

1. Where the popup lives

layer.popupTemplate = { title: "…", content: "…" };   // per layer - the usual case
graphic.popupTemplate = { … };                        // per graphic - client-side overrides
view.popupEnabled = false;                            // turn off click-to-open entirely
view.openPopup({ location, title, content });         // open it yourself
view.closePopup();

Changed in 5.0 - view.popup still exists as the Popup instance, but it is created lazily on first use. The supported control surface is view.popupEnabled, view.openPopup() and view.closePopup(). Older 4.x tutorials that do view.popup.autoOpenEnabled = false should become view.popupEnabled = false.

2. content accepts four things

// 1. A string with field substitution
content: "Population: {POPULATION}"

// 2. An array of content elements - the structured way
content: [
  { type: "fields", fieldInfos: [...] },
  { type: "media",  mediaInfos: [...] },
  { type: "text",   text: "…" },
]

// 3. A function - sync or async, returns a string, an HTMLElement, or elements
content: (event) => buildContent(event.graphic)

// 4. An HTMLElement directly
content: myDiv

Use 2 by default. Use 3 when you need to fetch something or compute across features. Use 1 for throwaway. Use 4 almost never - it bypasses the popup's own layout.

3. Field substitution and fieldInfos

popupTemplate: {
  title: "{NAME}, {STATE_NAME}",
  content: [{
    type: "fields",
    fieldInfos: [
      {
        fieldName: "POPULATION",
        label: "Population",
        format: { digitSeparator: true, places: 0 },
      },
      {
        fieldName: "MEDIAN_INCOME",
        label: "Median household income",
        format: { digitSeparator: true, places: 0 },
        // prefix/suffix render around the value
        prefix: "

format is the difference between a data dump and a report.

Option Values
digitSeparator true → 1,234,567
places decimal places
dateFormat short-date, long-date, short-date-short-time, long-month-day-year, day-short-month-year, and more

fieldInfos also controls order and visibility. Omit a field and it isn't shown; add visible: false to keep it available for substitution elsewhere without displaying it.

Without fieldInfos, the popup shows every field in outFields with raw names. That is the default that embarrasses you.

4. Content elements

text

{ type: "text", text: "<p>{NAME} was built in <b>{YEAR_BUILT}</b>.</p>" }

Supports a safe subset of HTML and field substitution. Good for a lead paragraph.

fields

As above. The workhorse.

media - charts and images

{
  type: "media",
  mediaInfos: [
    {
      type: "column-chart",
      title: "Population by decade",
      value: {
        fields: ["POP_1990", "POP_2000", "POP_2010", "POP_2020"],
        normalizeField: null,
      },
    },
    {
      type: "image",
      title: "{NAME}",
      caption: "Photographed {PHOTO_DATE}",
      value: { sourceURL: "{PHOTO_URL}", linkURL: "{DETAIL_URL}" },
    },
  ],
}

Chart types: bar-chart, column-chart, line-chart, pie-chart.

The charts are simple by design. They plot fields of one feature, not a series across features. If you need a real chart, use a function content element and render your own (Module 26).

attachments

{ type: "attachments", displayType: "preview" }   // or "list"

Requires layer.capabilities.data.supportsAttachment (Module 08). Photos attached to a feature in the field - the single most useful popup element in an inspection app.

relationship

{
  type: "relationship",
  relationshipId: 0,
  title: "Inspections",
  displayCount: 5,
  orderByFields: [{ field: "INSPECTION_DATE", order: "desc" }],
}

Shows related records from a service-defined relationship class. No code, no query - the service already knows.

expression (Arcade)

expressionInfos: [
  {
    name: "occupancyRate",
    title: "Occupancy",
    expression: `
      var total = $feature.TOTAL_UNITS;
      if (total == 0) { return "n/a"; }
      return Round(($feature.OCCUPIED_UNITS / total) * 100, 1) + "%";
    `,
  },
],
content: [{
  type: "fields",
  fieldInfos: [{ fieldName: "expression/occupancyRate", label: "Occupancy" }],
}],

Note the expression/ prefix - that is how a computed value is referenced. Arcade is Module 17; this is a preview of why it matters.

5. Popup actions

popupTemplate: {
  title: "{NAME}",
  content: "…",
  actions: [
    { id: "zoom-to",  title: "Zoom to",  className: "esri-icon-zoom-in-magnifying-glass" },
    { id: "buffer",   title: "1 km buffer", className: "esri-icon-radio-button-checked" },
    { id: "copy-url", title: "Copy link", className: "esri-icon-link" },
  ],
}
import * as reactiveUtils from "@arcgis/core/core/reactiveUtils.js";

// The Popup instance is created lazily; wait for it before wiring the handler.
await reactiveUtils.whenOnce(() => view.popup);

view.popup.on("trigger-action", async (event) => {
  const graphic = view.popup.selectedFeature;
  if (!graphic) return;

  switch (event.action.id) {
    case "zoom-to":
      await view.goTo({ target: graphic.geometry, scale: 5000 }).catch(() => {});
      break;
    case "buffer":
      await addBuffer(graphic.geometry, 1000);
      break;
    case "copy-url":
      await navigator.clipboard.writeText(shareUrlFor(graphic));
      break;
  }
});

Actions are how a popup becomes a control surface rather than a read-only card. "Zoom to", "Get directions", "Report a problem", "Show related" - all one action each.

6. PopupTemplate beyond the basics

popupTemplate: {
  title: "{NAME}",
  content: [...],
  outFields: ["*"],              // fields this template needs, independent of layer.outFields
  overwriteActions: true,        // replace default actions instead of appending
  returnGeometry: true,          // needed if content functions use the geometry
  lastEditInfoEnabled: false,    // hide the "last edited" footer
}

popupTemplate.outFields is the fix for "my popup shows {FIELD} literally." The layer's outFields controls what is downloaded for rendering; the popup can request more when it opens. Setting it here means you can keep layer.outFields tight and still have rich popups.

7. Popup docking and positioning

view.popup = {
  dockEnabled: true,
  dockOptions: {
    buttonEnabled: true,
    breakpoint: { width: 800 },   // auto-dock below this width
    position: "bottom-right",
  },
  visibleElements: {
    closeButton: true,
    featureNavigation: true,      // ← / → when a click hits several features
    actionBar: true,
    collapseButton: false,
  },
  collapseEnabled: false,
};

Docking matters on small screens. An anchored popup over a 400px-wide viewport covers the map. Set a breakpoint and it becomes a bottom sheet.


Build it

Use the US counties service - it has plenty of fields to work with.

https://services.arcgis.com/P3ePLMYs2RVChkJx/arcgis/rest/services/USA_Counties_Generalized/FeatureServer/0

Step 1 - The bad popup (so you can see the difference)

const counties = new FeatureLayer({
  url: COUNTIES_URL,
  outFields: ["*"],
  popupTemplate: { title: "{NAME}", content: "{*}" },   // {*} = every field
});

Click a county. You get 40 rows of POP2020, SQMI, FIPS, AVE_HH_SZ - machine names, unformatted numbers, no hierarchy. This is what most map apps ship.

Step 2 - Structure and format

const counties = new FeatureLayer({
  url: COUNTIES_URL,
  outFields: ["NAME", "STATE_NAME", "POPULATION", "POP_SQMI", "SQMI", "FIPS"],
  title: "US Counties",

  popupTemplate: {
    title: "{NAME} County, {STATE_NAME}",

    // Ask for extra fields only when a popup opens
    outFields: ["*"],

    content: [
      {
        type: "text",
        text: "<p><b>{NAME} County</b> covers {SQMI} square miles in {STATE_NAME}.</p>",
      },
      {
        type: "fields",
        fieldInfos: [
          {
            fieldName: "POPULATION",
            label: "Population",
            format: { digitSeparator: true, places: 0 },
          },
          {
            fieldName: "POP_SQMI",
            label: "Density",
            format: { digitSeparator: true, places: 1 },
            suffix: " / sq mi",
          },
          {
            fieldName: "SQMI",
            label: "Area",
            format: { digitSeparator: true, places: 0 },
            suffix: " sq mi",
          },
          { fieldName: "FIPS", label: "FIPS code" },
        ],
      },
    ],
  },
});

Reload and click. Compare the two. Same data, entirely different object.

Step 3 - Add a computed value with Arcade

popupTemplate: {
  title: "{NAME} County, {STATE_NAME}",
  outFields: ["*"],

  expressionInfos: [
    {
      name: "densityClass",
      title: "Settlement type",
      expression: `
        var d = $feature.POP_SQMI;
        if (IsEmpty(d))  { return "Unknown"; }
        if (d < 10)      { return "Frontier"; }
        if (d < 50)      { return "Rural"; }
        if (d < 500)     { return "Suburban"; }
        if (d < 2000)    { return "Urban"; }
        return "Dense urban";
      `,
    },
    {
      name: "stateShare",
      title: "Share of state population",
      expression: `
        // Sum the population of every county in this state, then express
        // this county as a percentage of it.
        var stateCounties = Filter(
          FeatureSetByName($map, "US Counties"),
          "STATE_NAME = @" + "'" + $feature.STATE_NAME + "'"
        );
        var stateTotal = Sum(stateCounties, "POPULATION");
        if (stateTotal == 0) { return "n/a"; }
        return Round(($feature.POPULATION / stateTotal) * 100, 2) + "%";
      `,
    },
  ],

  content: [
    { type: "text", text: "<p><b>{NAME} County</b> - {expression/densityClass}</p>" },
    {
      type: "fields",
      fieldInfos: [
        { fieldName: "POPULATION", label: "Population",
          format: { digitSeparator: true, places: 0 } },
        { fieldName: "expression/stateShare", label: "Share of state" },
        { fieldName: "POP_SQMI", label: "Density",
          format: { digitSeparator: true, places: 1 }, suffix: " / sq mi" },
      ],
    },
  ],
}

IsEmpty() is the Arcade null guard. Without it, a null density falls through every comparison and returns "Dense urban", which is wrong and silent.

The second expression queries other features via FeatureSetByName. This is where Arcade stops being string formatting and becomes genuinely powerful. Module 17.

Step 4 - Add a chart

{
  type: "media",
  mediaInfos: [
    {
      type: "column-chart",
      title: "Age distribution",
      caption: "Population by age band",
      value: {
        fields: ["AGE_UNDER5", "AGE_5_17", "AGE_18_64", "AGE_65UP"],
      },
    },
  ],
}

Verify those field names against your layer inspector from Module 08 first - they differ between service vintages, and a wrong field name renders an empty chart with no error.

Step 5 - Add actions

popupTemplate: {
  // …
  actions: [
    { id: "zoom-to",   title: "Zoom to",    className: "esri-icon-zoom-in-magnifying-glass" },
    { id: "neighbours",title: "Neighbours", className: "esri-icon-polygon" },
  ],
  overwriteActions: false,   // keep the default "Zoom to" as well? set true to replace
}
import * as reactiveUtils from "@arcgis/core/core/reactiveUtils.js";

await reactiveUtils.whenOnce(() => view.popup);

const handle = view.popup.on("trigger-action", async (event) => {
  const feature = view.popup.selectedFeature;
  if (!feature) return;

  if (event.action.id === "zoom-to") {
    await view.goTo({ target: feature.geometry, scale: 500000 }).catch(() => {});
  }

  if (event.action.id === "neighbours") {
    const { features } = await counties.queryFeatures({
      geometry: feature.geometry,
      spatialRelationship: "touches",
      outFields: ["NAME", "POPULATION"],
      returnGeometry: false,
    });
    const names = features.map((f) => f.attributes.NAME).join(", ");
    setStatus(`Neighbours: ${names || "none"}`);
  }
});

spatialRelationship: "touches" is a spatial query - Module 24. Note how little code a genuinely useful feature took.

Keep the handle. In a component you must remove it.

Step 6 - When a popup is the wrong container

Sometimes the information is too big, or the user needs it while panning, or you need your own UI framework's components inside it. Then: disable the popup, hitTest yourself, and render a panel.

view.popupEnabled = false;

const panel = document.getElementById("infoPanel");

view.on("click", async (event) => {
  const { results } = await view.hitTest(event, { include: counties });
  const hit = results.find((r) => r.type === "graphic");

  if (!hit) {
    panel.hidden = true;
    highlightHandle?.remove();
    highlightHandle = null;
    return;
  }

  // hitTest returns the drawn geometry, which may be generalised and may not
  // carry every attribute. Re-query by object id for the authoritative record.
  const { features } = await counties.queryFeatures({
    objectIds: [hit.graphic.attributes[counties.objectIdField]],
    outFields: ["*"],
    returnGeometry: false,
  });
  const attributes = features[0]?.attributes;
  if (!attributes) return;

  panel.hidden = false;
  panel.innerHTML = renderPanel(attributes);

  highlightHandle?.remove();
  highlightHandle = countiesLayerView.highlight(hit.graphic);
});

The re-query is not paranoia. hitTest gives you the graphic the renderer drew - which for a tiled or generalised layer may have a reduced attribute set. Querying by object id gets the real record.

Choosing between popup and panel:

Popup Panel
Anchored to the feature - spatial context is obvious More room; no overlap with the map
Zero layout work You control the layout entirely
Built-in feature navigation for multi-hits You build it
Closes on pan Stays open while the user explores
Hard to style deeply (shadow DOM) Your own DOM, your own CSS

Use popups by default. Move to a panel when the content exceeds roughly a screen-third or when users need it persistently.


How it works

How field substitution is resolved

When the popup opens, the SDK:

  1. Takes title and any string content
  2. Finds {TOKEN} occurrences
  3. Resolves each against, in order: the feature's attributes, expression/<name> results, and a few globals like {relationships/…}
  4. Applies the matching fieldInfos format
  5. Escapes the result before inserting it

Step 5 is why you cannot inject HTML through a field value - which is a security feature. If you need HTML from data, use a function content element and sanitise it yourself.

Why popupTemplate.outFields exists separately

layer.outFields governs the continuous download for every visible feature. Keeping it small is a real performance lever (Module 08).

popupTemplate.outFields governs a single extra request when one popup opens. It costs one round trip for one feature.

So: narrow layer.outFields, generous popupTemplate.outFields. Best of both.

Why the popup is lazily created in 5.0

Constructing the Popup widget pulls in a meaningful chunk of UI code. Most map views never open one. Creating it on first use keeps that out of the initial render path.

The consequence for you: view.popup may be null early. Use reactiveUtils.whenOnce(() => view.popup) before attaching handlers, or attach them after the first popup opens.

Multi-hit feature navigation

Click where three polygons overlap and the popup shows 1 of 3 with arrows. It works because openPopup accepts a set of features. If you build your own panel, you have to handle that case - it is easy to forget and produces "the wrong feature is selected" bug reports.


Common mistakes

{FIELD} rendered literally. The field isn't in layer.outFields or popupTemplate.outFields.

Showing null. Guard in Arcade with IsEmpty(), or use DefaultValue($feature.FIELD, "-").

Epoch integers where dates should be. Add format: { dateFormat: "short-date" } to the fieldInfo.

Unformatted big numbers. digitSeparator: true. 12841239 vs 12,841,239 is a real readability difference.

Using {*} in production. It shows every field including internal ones. It is a debugging tool.

Attaching to view.popup before it exists. whenOnce(() => view.popup).

Deep-styling the popup with descendant CSS. Shadow DOM. Use the documented CSS custom properties or build your own panel.

Trusting hitTest attributes for a detail view. Re-query by object id.


Exercises

Exercise 11.1 - Redesign a bad popup

Find a public feature service with 20+ fields (your city's open data portal is ideal). Build:

  1. A title that reads as a sentence, not a field name
  2. A lead text element summarising the feature in one line
  3. 5-7 fields with correct formatting, ordered by importance
  4. One Arcade-computed value that isn't in the data
  5. A chart, if the data supports one
  6. Two actions

Screenshot before and after. This is a portfolio piece.

Exercise 11.2 - Null-safe everything

Take your popup and deliberately query a feature with nulls in several fields. Fix every place that shows "null", "NaN", "undefined", "