;
}
export function Metric({ label, statePath, data }: MetricProps) {
const value = data ? getByPath(data, statePath) : undefined;
return (
{label}
{formatValue(value)}
);
}
```
--------------------------------
### Migrate Catalog Creation: createCatalog to defineCatalog
Source: https://json-render.dev/docs/migration
Replaced `createCatalog` and `generateSystemPrompt` with `defineSchema` + `defineCatalog`. Ensure you import `defineCatalog` and use the new structure for creating catalogs and generating prompts.
```javascript
import { createCatalog, generateSystemPrompt } from "@json-render/core";
const catalog = createCatalog({
name: "my-app",
components: { /* ... */ },
actions: { /* ... */ },
});
const prompt = generateSystemPrompt(catalog);
```
```javascript
import { defineCatalog } from "@json-render/core";
import { schema } from "@json-render/react/schema";
const catalog = defineCatalog(schema, {
components: { /* ... */ },
actions: { /* ... */ },
});
const prompt = catalog.prompt();
// Inline mode prompt (formerly "chat")
const inlinePrompt = catalog.prompt({ mode: "inline" });
```
--------------------------------
### Install @json-render/react-email
Source: https://json-render.dev/docs/changelog
Install the React Email renderer for json-render. Use this to generate HTML and plain-text emails from JSON specifications.
```bash
npm install @json-render/react-email
```
--------------------------------
### Get Array Length with $count
Source: https://json-render.dev/docs/api/directives
Use the $count directive to get the length of an array or string. Returns 0 for other types.
```json
{ "$count": { "$state": "/cart/items" } }
```
--------------------------------
### Install @json-render/vue
Source: https://json-render.dev/docs/changelog
Install the Vue 3 renderer for json-render. This provides full feature parity with the React renderer for Vue applications.
```bash
npm install @json-render/core @json-render/vue
```
--------------------------------
### Create a Custom Renderer with Directives
Source: https://json-render.dev/docs/directives
Shows an alternative way to set up a renderer using `createRenderer`, passing both catalog and components, and then applying custom directives to the created renderer instance.
```jsx
const MyRenderer = createRenderer(catalog, components);
```
--------------------------------
### Define Catalog and Registry
Source: https://json-render.dev/docs/api/react-three-fiber
Define a catalog with three-dimensional components and set up the registry for rendering. This example includes Box, Sphere, AmbientLight, DirectionalLight, and OrbitControls.
```javascript
import { defineCatalog } from "@json-render/core";
import { schema, defineRegistry } from "@json-render/react";
import {
threeComponentDefinitions,
threeComponents,
ThreeCanvas,
} from "@json-render/react-three-fiber";
const catalog = defineCatalog(schema, {
components: {
Box: threeComponentDefinitions.Box,
Sphere: threeComponentDefinitions.Sphere,
AmbientLight: threeComponentDefinitions.AmbientLight,
DirectionalLight: threeComponentDefinitions.DirectionalLight,
OrbitControls: threeComponentDefinitions.OrbitControls,
},
actions: {},
});
const { registry } = defineRegistry(catalog, {
components: {
Box: threeComponents.Box,
Sphere: threeComponents.Sphere,
AmbientLight: threeComponents.AmbientLight,
DirectionalLight: threeComponents.DirectionalLight,
OrbitControls: threeComponents.OrbitControls,
},
});
```
--------------------------------
### Get Current Repeat Index with $index
Source: https://json-render.dev/docs/data-binding
Use the $index expression inside a repeat to get the current array index (zero-based number).
```json
{
"type": "Text",
"props": { "content": { "$index": true } },
"children": []
}
```
--------------------------------
### AI-Generated JSON Spec Example
Source: https://json-render.dev/docs
An example of a JSON specification generated by AI, detailing the structure and properties of UI elements based on a defined catalog.
```json
{
"root": "card-1",
"elements": {
"card-1": {
"type": "Card",
"props": { "title": "Revenue Dashboard" },
"children": ["metric-1", "metric-2"]
},
"metric-1": {
"type": "Metric",
"props": { "label": "Total Revenue", "value": "$48,200" }
},
"metric-2": {
"type": "Metric",
"props": { "label": "Growth", "value": "+12%" }
}
}
}
```
--------------------------------
### Import xstateStoreStateStore
Source: https://json-render.dev/docs/api/xstate
Import the xstateStoreStateStore function from the @json-render/xstate package.
```javascript
import { xstateStoreStateStore } from "@json-render/xstate";
```
--------------------------------
### Create XState Store for json-render
Source: https://json-render.dev/docs/api/xstate
Create a StateStore backed by an @xstate/store atom. The atom should hold the json-render state model.
```javascript
import { createAtom } from "@xstate/store";
import { xstateStoreStateStore } from "@json-render/xstate";
import { StateProvider } from "@json-render/react";
const uiAtom = createAtom({ count: 0 });
const store = xstateStoreStateStore({ atom: uiAtom });
```
--------------------------------
### Install @json-render/react-three-fiber
Source: https://json-render.dev/docs/changelog
Install the React Three Fiber renderer for json-render. This allows JSON specs to be rendered as 3D scenes using React Three Fiber.
```bash
npm install @json-render/react-three-fiber
```
--------------------------------
### Generate Prompt with Directives
Source: https://json-render.dev/docs/directives
Illustrates how to generate a system prompt for AI, including custom directives, by calling the `prompt` method on the catalog object and passing the directives.
```javascript
const prompt = catalog.prompt({ directives });
```
--------------------------------
### Build User Prompt for Fresh Generation
Source: https://json-render.dev/docs/api/core
Construct a user prompt for AI generation. This example shows a basic prompt for creating a new application.
```typescript
import { buildUserPrompt } from '@json-render/core';
const userPrompt = buildUserPrompt({ prompt: "create a todo app" });
```
--------------------------------
### createMcpApp
Source: https://json-render.dev/docs/api/mcp
Create a fully-configured MCP server. This is the main entry point for setting up a json-render MCP application.
```APIDOC
## createMcpApp
### Description
Create a fully-configured MCP server. This is the main entry point.
### Method
```javascript
import { createMcpApp } from "@json-render/mcp";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import fs from "node:fs";
const server = createMcpApp({
name: "My Dashboard",
version: "1.0.0",
catalog: myCatalog,
html: fs.readFileSync("dist/index.html", "utf-8"),
});
await server.connect(new StdioServerTransport());
```
### Options
#### CreateMcpAppOptions
- `name` (string) - Required - Server name shown in client UIs
- `version` (string) - Required - Server version
- `catalog` (Catalog) - Required - json-render catalog defining available components
- `html` (string) - Required - Self-contained HTML for the iframe UI
- `tool` (McpToolOptions) - Optional - Tool name/title/description overrides
```
--------------------------------
### Directive Composition Example
Source: https://json-render.dev/docs/directives
An example of directive composition where a '$format' directive wraps a '$math' directive, which in turn uses a '$state' expression. This shows how directives can be nested and resolve values from state.
```json
{
"$format": "currency",
"value": {
"$math": "multiply",
"a": { "$state": "/price" },
"b": { "$state": "/qty" }
},
"currency": "USD"
}
```
--------------------------------
### Catalog Instance Methods
Source: https://json-render.dev/docs/api/core
The Catalog instance provides methods for AI prompt generation, validation, and schema export.
```APIDOC
## Catalog Instance Methods
The returned catalog provides methods for AI prompt generation, validation, and schema export:
### `prompt(options?: PromptOptions): string`
Generates an AI system prompt based on the catalog configuration and provided options.
### `validate(spec: unknown): SpecValidationResult`
Validates a given specification against the catalog's schema.
### `zodSchema(): z.ZodType`
Returns the Zod schema for the catalog's specifications.
### `jsonSchema(): object`
Exports the catalog's schema as a JSON Schema object.
### Example Usage
```typescript
// Generate AI system prompt
const systemPrompt = catalog.prompt({
customRules: ["Always use Card as root element"],
});
// Validate a spec from AI
const result = catalog.validate(aiOutput);
if (result.success) {
render(result.data);
} else {
console.error(result.error);
}
// Get Zod schema for custom validation
const schema = catalog.zodSchema();
const parsed = schema.safeParse(aiOutput);
// Export as JSON Schema (for structured outputs)
const jsonSchema = catalog.jsonSchema();
```
```
--------------------------------
### Example A2UI Message Structure
Source: https://json-render.dev/docs/a2ui
This is an example of an A2UI message using an adjacency list model. It includes components like Text, DateTimeInput, and Button, with ID references for easy patching.
```json
{
"surfaceUpdate": {
"surfaceId": "main",
"components": [
{
"id": "header",
"component": {
"Text": {
"text": {"literalString": "Book Your Table"},
"usageHint": "h1"
}
}
},
{
"id": "date-picker",
"component": {
"DateTimeInput": {
"label": {"literalString": "Select Date"},
"value": {"path": "/reservation/date"},
"enableDate": true
}
}
},
{
"id": "submit-btn",
"component": {
"Button": {
"child": "submit-text",
"action": {"name": "confirm_booking"}
}
}
},
{
"id": "submit-text",
"component": {
"Text": {"text": {"literalString": "Confirm Reservation"}}
}
}
]
}
}
```
--------------------------------
### Define Catalog with Components and Actions
Source: https://json-render.dev/docs/catalog
Use `defineCatalog` from `@json-render/core` to create a catalog. Define components with their props schemas using Zod, and actions with their parameters. The schema import is framework-specific.
```javascript
import { defineCatalog } from '@json-render/core';
import { schema } from '@json-render/react/schema'; // or '@json-render/react-native/schema'
import { z } from 'zod';
const catalog = defineCatalog(schema, {
components: {
// Define each component with its props schema
Card: {
props: z.object({
title: z.string(),
description: z.string().nullable(),
padding: z.enum(['sm', 'md', 'lg']).nullable(),
}),
slots: ["default"], // Can contain other components
description: "Container card for grouping content",
},
Metric: {
props: z.object({
label: z.string(),
value: z.union([z.string(), z.number()]),
format: z.enum(['currency', 'percent', 'number']),
}),
description: "Display a single metric value",
},
},
actions: {
submit_form: {
params: z.object({
formId: z.string(),
}),
description: 'Submit a form',
},
export_data: {
params: z.object({
format: z.enum(['csv', 'pdf', 'json']),
}),
description: 'Export data in various formats',
},
},
});
```
--------------------------------
### Install json-render React-Email Skill
Source: https://json-render.dev/docs/skills
Installs the React-Email skill for json-render, enabling AI agents to render JSON specs as HTML or plain-text emails. This skill features an email-specific registry and rendering pipeline.
```bash
npx skills add vercel-labs/json-render --skill react-email
```
--------------------------------
### Set up JsonUIProvider for State and Actions
Source: https://json-render.dev/docs/api/svelte
The JsonUIProvider wraps components, providing state management, visibility, validation, and action handling. It requires initial state and handler configurations.
```svelte
```
--------------------------------
### Install json-render Codegen Skill
Source: https://json-render.dev/docs/skills
Installs the Codegen skill for json-render, teaching AI agents how to export UI specs as framework-specific source code. This skill covers the codegen pipeline and custom exporter creation.
```bash
npx skills add vercel-labs/json-render --skill codegen
```
--------------------------------
### Create a Redux-backed StateStore
Source: https://json-render.dev/docs/api/redux
Configure and create a `StateStore` instance using Redux. This involves providing the Redux store, a selector to isolate the json-render state slice, and a dispatch function to update it.
```javascript
import { configureStore, createSlice } from "@reduxjs/toolkit";
import { reduxStateStore } from "@json-render/redux";
import { StateProvider } from "@json-render/react";
const uiSlice = createSlice({
name: "ui",
initialState: { count: 0 } as Record,
reducers: {
replaceUiState: (_state, action) => action.payload,
},
});
const reduxStore = configureStore({
reducer: { ui: uiSlice.reducer },
});
const store = reduxStateStore({
store: reduxStore,
selector: (state) => state.ui,
dispatch: (next, s) => s.dispatch(uiSlice.actions.replaceUiState(next)),
});
```
```javascript
{/* json-render reads/writes go through Redux */}
```
--------------------------------
### Install json-render Svelte Skill
Source: https://json-render.dev/docs/skills
Installs the Svelte skill for json-render, allowing AI agents to render JSON specs as Svelte 5 component trees. This skill covers the Svelte renderer API and component registration.
```bash
npx skills add vercel-labs/json-render --skill svelte
```
--------------------------------
### Setup Inline Mode
Source: https://json-render.dev/docs/generation-modes
Enable inline mode by setting the `mode` option to 'inline' in the system prompt. This mode allows for conversational responses alongside UI patches.
```typescript
import { streamText } from "ai";
import { pipeJsonRender } from "@json-render/core";
import { createUIMessageStream, createUIMessageStreamResponse } from "ai";
// Enable inline mode
const systemPrompt = catalog.prompt({ mode: "inline" });
const result = streamText({
model: yourModel,
system: systemPrompt,
messages,
});
// In your API route, pipe the stream through pipeJsonRender
// to separate text from JSONL patches
const stream = createUIMessageStream({
execute: async ({ writer }) => {
writer.merge(pipeJsonRender(result.toUIMessageStream()));
},
});
return createUIMessageStreamResponse({ stream });
```
--------------------------------
### Install json-render React-Native Skill
Source: https://json-render.dev/docs/skills
Installs the React Native skill for json-render, empowering AI agents to render JSON specs as native mobile UIs. This skill includes the native component registry and addresses platform-specific considerations.
```bash
npx skills add vercel-labs/json-render --skill react-native
```
--------------------------------
### SolidJS Renderer Setup
Source: https://json-render.dev/docs/renderers
Implement the SolidJS renderer for fine-grained reactivity and state bindings. This renderer supports validation, visibility, and event-driven actions, translating JSON specs into SolidJS component trees.
```javascript
import { defineRegistry, Renderer } from "@json-render/solid";
import { schema } from "@json-render/solid/schema";
const { registry } = defineRegistry(catalog, {
components: {
Card: (renderProps) => {renderProps.children}
,
},
});
;
```
--------------------------------
### Install json-render React Skill
Source: https://json-render.dev/docs/skills
Installs the React skill for json-render, enabling AI agents to render JSON specs as React component trees. This skill supports custom component registries, client-side interactivity, and state management.
```bash
npx skills add vercel-labs/json-render --skill react
```