UI

React and JSON integration

Share one validated configuration across React and JSON rendering, with data and effects owned by your application.

Use a JSON document to describe the interface and React to connect it to your application. A validated dropdown configuration can become direct <DropdownMenu {...config} /> props or a DropdownMenu element rendered by CompositionView. Both paths render the same React component.

Try the integration

APPLICATION OWNED

Quarterly report

A local asynchronous demo service updates a subscribed cache. Downloads create real files. No remote API is used.

Report cache ready. Choose an action.

Live cache · 0 refreshes · CSV export
PeriodRecords
Current quarter128
Previous quarter (archived)96
Agent configuration · revision 0

This editor accepts composition updates. Stable item IDs preserve checkbox and radio choices. Pending state and report data stay with the host.

Current agent document
{
  "revision": 0,
  "spec": {
    "root": "report-menu",
    "elements": {
      "report-menu": {
        "type": "DropdownMenu",
        "props": {
          "label": "Report actions",
          "items": [
            {
              "kind": "action",
              "id": "refresh",
              "label": "Refresh report",
              "action": "refresh_report",
              "closeOnSelect": false,
              "loadingLabel": "Refreshing…"
            },
            {
              "kind": "action",
              "id": "download",
              "label": "Download report",
              "action": "download_report",
              "closeOnSelect": false,
              "loadingLabel": "Preparing download…"
            },
            {
              "kind": "separator",
              "id": "divider"
            },
            {
              "kind": "checkbox",
              "id": "archived",
              "label": "Include archived",
              "defaultChecked": true
            },
            {
              "kind": "group",
              "id": "format",
              "label": "Download format",
              "items": [
                {
                  "kind": "radio",
                  "id": "csv",
                  "label": "CSV",
                  "defaultChecked": true
                },
                {
                  "kind": "radio",
                  "id": "json",
                  "label": "JSON"
                }
              ]
            }
          ],
          "placement": "bottom-start",
          "size": "md",
          "variant": "outline",
          "recipe": "studio",
          "motion": "subtle",
          "closeOnSelect": true,
          "loopFocus": true,
          "disabled": false,
          "defaultOpen": false
        },
        "children": []
      }
    }
  }
}

Switch rendering modes, change a checkbox or radio choice, apply an edit, and remount the preview. The example keeps one configuration document and one selection store. Refresh demonstrates an asynchronous host data cache; exporting downloads CSV or JSON according to the selected format. The local refresh service needs no credentials. Use the failure control to inspect the error path.

The JSON panel shows the agent's configuration document. The React code connects that document to current host data, selections and callbacks. Both rendering modes receive the same validated effective props and shared selections. Runtime loading and cached results remain in the host, so they can change while the configuration revision stays the same.

Decide who owns each value

ValueOwnerHow it reaches the interface
Labels, item structure, action names, layout, theme and motionAgent configurationValidated JSON becomes component props.
Checkbox and radio choicesUser state, held by the hostControlled checked / onCheckedChange, or the composition state binding.
API results, cache, pending requests and errorsApplicationThe host derives current props and visible feedback from its data.
Fetches, downloads and mutationsApplication action handlersA named onAction event selects a registered host function.
Open popup and keyboard focusMounted UI instanceInternal component state, or explicit React controls when needed.

defaultChecked initializes a choice; it does not replace a user's current selection. Similarly, editing defaultOpen does not reopen an existing instance. Keep callbacks, credentials, service clients and cache objects in application code.

Large query results

A Table accepts up to 500 columns and 10,000 rows in both direct React props and composition documents. createComposition and applyCompositionUpdate give its columns, rows and defaultSelectedKeys separate finite JSON data budgets. Full-spec replacements, element/props replacements and JSON Patch updates to these collections preserve the complete result. Every item is still validated against the Table schema; unknown fields, invalid IDs, non-JSON values and excessive nesting are rejected atomically. Data allowances are shared across each request so repeated operations cannot multiply them.

Other component props retain the normal composition envelope budget of 20,000 JSON nodes and 200,000 characters. Components declare any larger collection allowance in definition metadata (dataLimits); this is host validation metadata, not an agent-settable prop. Application transport and model output limits remain application concerns. Fetch query results in your host and supply them as data rather than asking a model to reproduce them.

Receive an edit against the latest state

Parse the completed model response, validate its candidate, and commit only a successful result. Use a reducer or another serialized update boundary so incoming edits see the latest configuration. A response captured before another edit may be stale.

This small direct React example uses only public package exports. The receive function is the boundary for parsed model output; your transport calls it when a response completes.

'use client'

import { useReducer } from 'react'
import { DropdownMenu, resolveDropdown } from '@uthereal/ui/dropdown-menu'
import { applyDropdownEdit } from '@uthereal/ui/agent'

const allowedActions = ['export_csv']
const initial = {
  config: resolveDropdown({
    label: 'Export',
    items: [
      {
        kind: 'action',
        id: 'csv',
        label: 'Download CSV',
        action: 'export_csv',
      },
    ],
  }),
  errors: [] as string[],
}

export function ExportMenu({ downloadCsv }: { downloadCsv: () => void }) {
  const [state, receive] = useReducer(
    (current: typeof initial, output: unknown) => {
      const result = applyDropdownEdit(current.config, output, allowedActions)
      return result.success
        ? { config: result.config, errors: [] }
        : { ...current, errors: result.errors }
    },
    initial,
  )

  return (
    <>
      <DropdownMenu
        {...state.config}
        onAction={(action) => {
          if (action === 'export_csv') downloadCsv()
        }}
      />
      <button onClick={() => receive({ label: 'Report exports' })}>
        Apply example edit
      </button>
      <p role="status">{state.errors.join('; ')}</p>
    </>
  )
}

An invalid edit preserves the working configuration and produces errors to show or send back to the model. A valid configuration update changes presentation; it does not call downloadCsv. That function runs only when the user selects its action.

Single edits and composition patches

The two update formats have different semantics:

BoundaryUpdateObject behavior
applyDropdownEdit or applyEditPartial component argumentsMerge supplied nested option fields; arrays replace. Top-level null resets a defaulted setting or removes an optional one.
applyCompositionUpdate or a custom kit's applyCompositionUpdate{ baseRevision, patch } or { baseRevision, spec }JSON Patch add / replace replaces the addressed value. A full spec replaces the spec.

For a dropdown edit, { theme: { tokens: { popupRadius: 20 } } } preserves other theme overrides. For a composition patch, replacing /elements/menu/props/theme replaces the whole theme object. To preserve its other fields, replace the existing /elements/menu/props/theme/tokens/popupRadius path. Use add when creating a missing object and remove to clear an override. Composition patches do not use the component edit format's null reset operation.

Composition updates must include the current baseRevision. The validator checks the full candidate, registered actions and tree structure before returning the next document. Stale revisions and invalid candidates leave the current document intact. Apply each response against the latest document; expose returned errors for a retry. See Building with agents for the reducer and patch envelope.

Connect host data without giving the agent the cache

The application owns fetching, cache lifetime, retries and action status. Derive effective props from the current validated configuration plus the latest host snapshot. For example, mark a refresh action as loading while its request is pending, and use cached results to supply the current item labels or availability.

Keep that derivation separate from the editable agent document. Apply host-owned fields after configuration fields, then validate the entire projected candidate before passing it to either renderer. Validate action names as well as prop shapes. If projection fails, retain the last valid view and report the error. An incoming agent edit must not replace an in-flight request or cached result merely because it contains an older loading, label or items value.

The library has no fetch or cache policy. In a real application, replace the example's local refresh service with your API client or query cache, keep its subscription in the host, and map named actions to your existing commands. An allowed action name identifies a handler; the application still determines its behavior and permissions.

Composition props are literal values accepted by each component schema. The composition contract does not evaluate data expressions, call API URLs, run watchers, or let the agent write arbitrary user state. For host data in a composition, project a validated spec in application code or use a stable custom registry component that supplies the required React props. Keep the registry's component identities stable.

Preserve the state you intend to keep

For direct React, hold checked in the host and wire onCheckedChange; control open separately if its lifetime must extend beyond the mounted menu. For composition, create the state store once and reuse it with CompositionView. The dropdown binding reconciles checkbox and radio values by stable item ID; existing selections win over edited defaults, removed entries are discarded, and new entries initialize from their defaults.

Keep the component ID, item IDs and host store stable across edits. A different component ID addresses different stored state. Moving an element to another parent, switching rendering paths, or changing a React key can remount it. External selections can survive; popup state and focus follow the mounted instance. The example deliberately shares its controlled selection store between direct and composition rendering; separate stores would be independent.

Reuse the example

The integration component source contains the two render paths, shared selection store and browser download handler. The host model source contains the document update boundary, validated runtime projection and local data service. Copy the pieces relevant to your host; use public @uthereal/ui/dropdown-menu, @uthereal/ui/agent, @uthereal/ui/composition and @uthereal/ui/composition/react imports in application code.

For model wiring, supply the edit JSON Schema for a single component, or the matching kit's prompt and update JSON Schema for compositions. Send only the components and action names the screen offers. See Connect your model and the dropdown reference.

On this page