@easyops-cn/a2ui-react
v0.0.10
Published
A2UI React Renderer
Downloads
1,163
Readme
A2UI React Renderer
A React renderer library for A2UI protocol.
Supports all components in A2UI standard catalog out of the box. Built with shadcn/ui and Tailwind CSS.
Currently A2UI protocol v0.8 is fully supported. Work on v0.9 is in progress.
Installation
npm install @easyops-cn/a2ui-reactUsage
First, use the @source directive to tell Tailwind to scan the library code for class names in your global CSS:
@source "../node_modules/@easyops-cn/a2ui-react";Next, use A2UIProvider and A2UIRenderer to render A2UI messages:
import {
A2UIProvider,
A2UIRenderer,
type A2UIMessage,
type A2UIAction,
} from '@easyops-cn/a2ui-react/0.8'
function App() {
const messages: A2UIMessage[] = []
const handleAction = (action: A2UIAction) => {
console.log('Action received:', action)
}
return (
<A2UIProvider messages={messages}>
<A2UIRenderer onAction={handleAction} />
</A2UIProvider>
)
}Custom components
You can override default components or add new custom components via the components prop on A2UIProvider, which takes a Map<string, React.ComponentType>.
import {
A2UIProvider,
A2UIRenderer,
type A2UIMessage,
type A2UIAction,
} from '@easyops-cn/a2ui-react/0.8'
const ComponentsMap = new Map<string, React.ComponentType<any>>([
// Override default Button component with a custom one
['Button', CustomButtonComponent],
// Add a new custom Switch component
['Switch', CustomSwitchComponent],
])
function App() {
return (
<A2UIProvider components={ComponentsMap} messages={messages}>
<A2UIRenderer onAction={handleAction} />
</A2UIProvider>
)
}Custom button component with action dispatch:
import {
useDispatchAction,
ComponentRenderer,
type ButtonComponentProps,
} from '@easyops-cn/a2ui-react/0.8'
export function CustomButtonComponent({
surfaceId,
componentId,
child,
action,
}: ButtonComponentProps) {
const dispatchAction = useDispatchAction()
const handleClick = () => {
if (action) {
dispatchAction(surfaceId, componentId, action)
}
}
return (
<button onClick={handleClick}>
<ComponentRenderer surfaceId={surfaceId} componentId={child} />
</button>
)
}Custom switch component with data binding:
import { useDataBinding, useFormBinding } from '@easyops-cn/a2ui-react/0.8'
export function CustomSwitchComponent({
surfaceId,
componentId,
label,
value,
}: SwitchComponentProps) {
const labelText = useDataBinding<string>(surfaceId, label, '')
const [checked, setChecked] = useFormBinding<boolean>(surfaceId, value, false)
const handleChange = (newChecked: boolean) => {
setChecked(newChecked)
}
return (
<Switch checked={checked} onChange={handleChange}>
{labelText}
</Switch>
)
}