react

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

@json-render/react

@json-render/react

React renderer that converts JSON specs into React component trees.
可将JSON规范转换为React组件树的React渲染器。

Quick Start

快速开始

typescript
import { defineRegistry, Renderer } from "@json-render/react";
import { catalog } from "./catalog";

const { registry } = defineRegistry(catalog, {
  components: {
    Card: ({ props, children }) => <div>{props.title}{children}</div>,
  },
});

function App({ spec }) {
  return <Renderer spec={spec} registry={registry} />;
}
typescript
import { defineRegistry, Renderer } from "@json-render/react";
import { catalog } from "./catalog";

const { registry } = defineRegistry(catalog, {
  components: {
    Card: ({ props, children }) => <div>{props.title}{children}</div>,
  },
});

function App({ spec }) {
  return <Renderer spec={spec} registry={registry} />;
}

Creating a Catalog

创建组件目录

typescript
import { defineCatalog } from "@json-render/core";
import { schema } from "@json-render/react/schema";
import { defineRegistry } from "@json-render/react";
import { z } from "zod";

// Create catalog with props schemas
export const catalog = defineCatalog(schema, {
  components: {
    Button: {
      props: z.object({
        label: z.string(),
        variant: z.enum(["primary", "secondary"]).nullable(),
      }),
      description: "Clickable button",
    },
    Card: {
      props: z.object({ title: z.string() }),
      description: "Card container with title",
    },
  },
});

// Define component implementations with type-safe props
const { registry } = defineRegistry(catalog, {
  components: {
    Button: ({ props }) => (
      <button className={props.variant}>{props.label}</button>
    ),
    Card: ({ props, children }) => (
      <div className="card">
        <h2>{props.title}</h2>
        {children}
      </div>
    ),
  },
});
typescript
import { defineCatalog } from "@json-render/core";
import { schema } from "@json-render/react/schema";
import { defineRegistry } from "@json-render/react";
import { z } from "zod";

// 基于属性schema创建组件目录
export const catalog = defineCatalog(schema, {
  components: {
    Button: {
      props: z.object({
        label: z.string(),
        variant: z.enum(["primary", "secondary"]).nullable(),
      }),
      description: "可点击的按钮",
    },
    Card: {
      props: z.object({ title: z.string() }),
      description: "带标题的卡片容器",
    },
  },
});

// 定义类型安全属性的组件实现
const { registry } = defineRegistry(catalog, {
  components: {
    Button: ({ props }) => (
      <button className={props.variant}>{props.label}</button>
    ),
    Card: ({ props, children }) => (
      <div className="card">
        <h2>{props.title}</h2>
        {children}
      </div>
    ),
  },
});

Spec Structure (Element Tree)

规范结构(元素树)

The React schema uses an element tree format:
json
{
  "root": {
    "type": "Card",
    "props": { "title": "Hello" },
    "children": [
      { "type": "Button", "props": { "label": "Click me" } }
    ]
  }
}
React schema使用元素树格式:
json
{
  "root": {
    "type": "Card",
    "props": { "title": "Hello" },
    "children": [
      { "type": "Button", "props": { "label": "Click me" } }
    ]
  }
}

Visibility Conditions

可见性条件

Use
visible
on elements to show/hide based on state. New syntax:
{ "$state": "/path" }
,
{ "$state": "/path", "eq": value }
,
{ "$state": "/path", "not": true }
,
{ "$and": [cond1, cond2] }
for AND,
{ "$or": [cond1, cond2] }
for OR. Helpers:
visibility.when("/path")
,
visibility.unless("/path")
,
visibility.eq("/path", val)
,
visibility.and(cond1, cond2)
,
visibility.or(cond1, cond2)
.
在元素上使用
visible
属性,可基于状态显示/隐藏元素。新增语法:
{ "$state": "/path" }
{ "$state": "/path", "eq": value }
{ "$state": "/path", "not": true }
,逻辑与用
{ "$and": [cond1, cond2] }
,逻辑或用
{ "$or": [cond1, cond2] }
。辅助方法:
visibility.when("/path")
visibility.unless("/path")
visibility.eq("/path", val)
visibility.and(cond1, cond2)
visibility.or(cond1, cond2)

Providers

提供者

ProviderPurpose
StateProvider
Share state across components (JSON Pointer paths). Accepts optional
store
prop for controlled mode.
ActionProvider
Handle actions dispatched via the event system
VisibilityProvider
Enable conditional rendering based on state
ValidationProvider
Form field validation
提供者用途
StateProvider
跨组件共享状态(JSON Pointer路径)。支持可选
store
属性用于受控模式。
ActionProvider
处理通过事件系统派发的动作
VisibilityProvider
启用基于状态的条件渲染
ValidationProvider
表单字段验证

External Store (Controlled Mode)

外部状态存储(受控模式)

Pass a
StateStore
to
StateProvider
(or
JSONUIProvider
/
createRenderer
) to use external state management (Redux, Zustand, XState, etc.):
tsx
import { createStateStore, type StateStore } from "@json-render/react";

const store = createStateStore({ count: 0 });

<StateProvider store={store}>{children}</StateProvider>

// Mutate from anywhere — React re-renders automatically:
store.set("/count", 1);
When
store
is provided,
initialState
and
onStateChange
are ignored.
StateProvider
(或
JSONUIProvider
/
createRenderer
)传入
StateStore
即可使用外部状态管理工具(Redux、Zustand、XState等):
tsx
import { createStateStore, type StateStore } from "@json-render/react";

const store = createStateStore({ count: 0 });

<StateProvider store={store}>{children}</StateProvider>

// 可在任意位置修改状态 —— React会自动重新渲染:
store.set("/count", 1);
当提供了
store
时,
initialState
onStateChange
会被忽略。

Dynamic Prop Expressions

动态属性表达式

Any prop value can be a data-driven expression resolved by the renderer before components receive props:
  • { "$state": "/state/key" }
    - reads from state model (one-way read)
  • { "$bindState": "/path" }
    - two-way binding: reads from state and enables write-back. Use on the natural value prop (value, checked, pressed, etc.) of form components.
  • { "$bindItem": "field" }
    - two-way binding to a repeat item field. Use inside repeat scopes.
  • { "$cond": <condition>, "$then": <value>, "$else": <value> }
    - conditional value
  • { "$template": "Hello, ${/name}!" }
    - interpolates state values into strings
  • { "$computed": "fn", "args": { ... } }
    - calls registered functions with resolved args
json
{
  "type": "Input",
  "props": {
    "value": { "$bindState": "/form/email" },
    "placeholder": "Email"
  }
}
Components do not use a
statePath
prop for two-way binding. Use
{ "$bindState": "/path" }
on the natural value prop instead.
Components receive already-resolved props. For two-way bound props, use the
useBoundProp
hook with the
bindings
map the renderer provides.
Register
$computed
functions via the
functions
prop on
JSONUIProvider
or
createRenderer
:
tsx
<JSONUIProvider
  functions={{ fullName: (args) => `${args.first} ${args.last}` }}
>
任意属性值都可以是数据驱动的表达式,渲染器会在组件接收属性前完成解析:
  • { "$state": "/state/key" }
    - 从状态模型读取数据(单向读取)
  • { "$bindState": "/path" }
    - 双向绑定:从状态读取数据并支持回写。用于表单组件的原生值属性(value、checked、pressed等)。
  • { "$bindItem": "field" }
    - 双向绑定到循环项字段,在循环作用域内使用。
  • { "$cond": <condition>, "$then": <value>, "$else": <value> }
    - 条件取值
  • { "$template": "Hello, ${/name}!" }
    - 将状态值插值到字符串中
  • { "$computed": "fn", "args": { ... } }
    - 调用注册的函数并传入解析后的参数
json
{
  "type": "Input",
  "props": {
    "value": { "$bindState": "/form/email" },
    "placeholder": "邮箱"
  }
}
组件无需使用
statePath
属性实现双向绑定,直接在原生值属性上使用
{ "$bindState": "/path" }
即可。
组件接收到的是已经解析完成的属性。对于双向绑定的属性,可结合渲染器提供的
bindings
映射使用
useBoundProp
hook。
可通过
JSONUIProvider
createRenderer
functions
属性注册
$computed
函数:
tsx
<JSONUIProvider
  functions={{ fullName: (args) => `${args.first} ${args.last}` }}
>

Event System

事件系统

Components use
emit
to fire named events, or
on()
to get an event handle with metadata. The element's
on
field maps events to action bindings:
tsx
// Simple event firing
Button: ({ props, emit }) => (
  <button onClick={() => emit("press")}>{props.label}</button>
),

// Event handle with metadata (e.g. preventDefault)
Link: ({ props, on }) => {
  const click = on("click");
  return (
    <a href={props.href} onClick={(e) => {
      if (click.shouldPreventDefault) e.preventDefault();
      click.emit();
    }}>{props.label}</a>
  );
},
json
{
  "type": "Button",
  "props": { "label": "Submit" },
  "on": { "press": { "action": "submit" } }
}
The
EventHandle
returned by
on()
has:
emit()
,
shouldPreventDefault
(boolean), and
bound
(boolean).
组件可使用
emit
触发命名事件,或使用
on()
获取带元数据的事件句柄。元素的
on
字段将事件映射到动作绑定:
tsx
// 简单事件触发
Button: ({ props, emit }) => (
  <button onClick={() => emit("press")}>{props.label}</button>
),

// 带元数据的事件句柄(例如preventDefault)
Link: ({ props, on }) => {
  const click = on("click");
  return (
    <a href={props.href} onClick={(e) => {
      if (click.shouldPreventDefault) e.preventDefault();
      click.emit();
    }}>{props.label}</a>
  );
},
json
{
  "type": "Button",
  "props": { "label": "提交" },
  "on": { "press": { "action": "submit" } }
}
on()
返回的
EventHandle
包含:
emit()
shouldPreventDefault
(布尔值)和
bound
(布尔值)。

State Watchers

状态监听器

Elements can declare a
watch
field (top-level, sibling of type/props/children) to trigger actions when state values change:
json
{
  "type": "Select",
  "props": { "value": { "$bindState": "/form/country" }, "options": ["US", "Canada"] },
  "watch": { "/form/country": { "action": "loadCities" } },
  "children": []
}
元素可声明
watch
字段(与type/props/children同级的顶级字段),在状态值变化时触发动作:
json
{
  "type": "Select",
  "props": { "value": { "$bindState": "/form/country" }, "options": ["US", "加拿大"] },
  "watch": { "/form/country": { "action": "loadCities" } },
  "children": []
}

Built-in Actions

内置动作

The
setState
,
pushState
,
removeState
, and
validateForm
actions are built into the React schema and handled automatically by
ActionProvider
. They are injected into AI prompts without needing to be declared in catalog
actions
:
json
{ "action": "setState", "params": { "statePath": "/activeTab", "value": "home" } }
{ "action": "pushState", "params": { "statePath": "/items", "value": { "text": "New" } } }
{ "action": "removeState", "params": { "statePath": "/items", "index": 0 } }
{ "action": "validateForm", "params": { "statePath": "/formResult" } }
validateForm
validates all registered fields and writes
{ valid, errors }
to state.
Note:
statePath
in action params (e.g.
setState.statePath
) targets the mutation path. Two-way binding in component props uses
{ "$bindState": "/path" }
on the value prop, not
statePath
.
setState
pushState
removeState
validateForm
动作是React schema内置的,由
ActionProvider
自动处理。它们会被自动注入到AI提示词中,无需在组件目录的
actions
中声明:
json
{ "action": "setState", "params": { "statePath": "/activeTab", "value": "home" } }
{ "action": "pushState", "params": { "statePath": "/items", "value": { "text": "新建" } } }
{ "action": "removeState", "params": { "statePath": "/items", "index": 0 } }
{ "action": "validateForm", "params": { "statePath": "/formResult" } }
validateForm
会验证所有注册的字段,并将
{ valid, errors }
写入状态。
注意:动作参数中的
statePath
(例如
setState.statePath
)指向的是修改路径。组件属性的双向绑定是在值属性上使用
{ "$bindState": "/path" }
,而非
statePath

useBoundProp

useBoundProp

For form components that need two-way binding, use
useBoundProp
with the
bindings
map the renderer provides when a prop uses
{ "$bindState": "/path" }
or
{ "$bindItem": "field" }
:
tsx
import { useBoundProp } from "@json-render/react";

Input: ({ element, bindings }) => {
  const [value, setValue] = useBoundProp<string>(
    element.props.value,
    bindings?.value
  );
  return (
    <input
      value={value ?? ""}
      onChange={(e) => setValue(e.target.value)}
    />
  );
},
useBoundProp(propValue, bindingPath)
returns
[value, setValue]
. The
value
is the resolved prop;
setValue
writes back to the bound state path (no-op if not bound).
对于需要双向绑定的表单组件,当属性使用了
{ "$bindState": "/path" }
{ "$bindItem": "field" }
时,可结合渲染器提供的
bindings
映射使用
useBoundProp
tsx
import { useBoundProp } from "@json-render/react";

Input: ({ element, bindings }) => {
  const [value, setValue] = useBoundProp<string>(
    element.props.value,
    bindings?.value
  );
  return (
    <input
      value={value ?? ""}
      onChange={(e) => setValue(e.target.value)}
    />
  );
},
useBoundProp(propValue, bindingPath)
返回
[value, setValue]
value
是解析后的属性值;
setValue
会将值回写到绑定的状态路径(如果没有绑定则无操作)。

BaseComponentProps

BaseComponentProps

For building reusable component libraries not tied to a specific catalog (e.g.
@json-render/shadcn
):
typescript
import type { BaseComponentProps } from "@json-render/react";

const Card = ({ props, children }: BaseComponentProps<{ title?: string }>) => (
  <div>{props.title}{children}</div>
);
用于构建不绑定特定组件目录的可复用组件库(例如
@json-render/shadcn
):
typescript
import type { BaseComponentProps } from "@json-render/react";

const Card = ({ props, children }: BaseComponentProps<{ title?: string }>) => (
  <div>{props.title}{children}</div>
);

defineRegistry

defineRegistry

defineRegistry
conditionally requires the
actions
field only when the catalog declares actions. Catalogs with
actions: {}
can omit it.
仅当组件目录声明了actions时,
defineRegistry
才会要求传入
actions
字段。如果目录的
actions: {}
则可以省略该字段。

Key Exports

核心导出项

ExportPurpose
defineRegistry
Create a type-safe component registry from a catalog
Renderer
Render a spec using a registry
schema
Element tree schema (includes built-in state actions: setState, pushState, removeState, validateForm)
useStateStore
Access state context
useStateValue
Get single value from state
useBoundProp
Two-way binding for
$bindState
/
$bindItem
expressions
useActions
Access actions context
useAction
Get a single action dispatch function
useOptionalValidation
Non-throwing variant of useValidation (returns null if no provider)
useUIStream
Stream specs from an API endpoint
createStateStore
Create a framework-agnostic in-memory
StateStore
StateStore
Interface for plugging in external state management
BaseComponentProps
Catalog-agnostic base type for reusable component libraries
EventHandle
Event handle type (
emit
,
shouldPreventDefault
,
bound
)
ComponentContext
Typed component context (catalog-aware)
导出项用途
defineRegistry
基于组件目录创建类型安全的组件注册表
Renderer
使用注册表渲染规范
schema
元素树schema(包含内置状态动作:setState、pushState、removeState、validateForm)
useStateStore
访问状态上下文
useStateValue
从状态中获取单个值
useBoundProp
$bindState
/
$bindItem
表达式提供双向绑定
useActions
访问动作上下文
useAction
获取单个动作派发函数
useOptionalValidation
非抛出异常版的useValidation(如果没有提供者则返回null)
useUIStream
从API接口流式获取规范
createStateStore
创建框架无关的内存级
StateStore
StateStore
接入外部状态管理的接口
BaseComponentProps
可复用组件库的无目录依赖基础类型
EventHandle
事件句柄类型(
emit
shouldPreventDefault
bound
ComponentContext
类型化组件上下文(感知组件目录)