GitHubX

JSX Renderer

PreviousNext

A component that renders JSX strings with access to Tailwind CSS, shadcn components, and Lucide icons.

Installation

pnpm dlx shadcn@latest add jsx-renderer

About

The JSX Renderer component allows you to render JSX strings dynamically with built-in error handling, state management, and component injection. It's particularly useful for AI-generated UI components or when you need to render JSX from external sources.

Use Cases

  • AI-Generated UI: Render user interfaces generated by AI models
  • Code Preview: Display rendered JSX in documentation or playgrounds

States

The JSX Renderer supports different states that affect its appearance and behavior:

  • interactive: Default state with full interactivity
  • disabled: Reduces opacity and disables pointer events
  • read-only: Disables pointer events but maintains visibility
  • streaming: Shows a pulsing animation with reduced opacity
  • error: Adds a red border for error indication

Usage

import { JsxRenderer } from "@/components/ui/jsx-renderer"
import { Button } from "@/components/ui/button"
import { Card } from "@/components/ui/card"
 
export function MyComponent() {
  const jsxString = `
    <Card className="p-4">
      <h2 className="text-lg font-semibold">Hello World</h2>
      <Button>Click me</Button>
    </Card>
  `
 
  return (
    <JsxRenderer
      jsx={jsxString}
      components={{
        Button,
        Card,
      }}
    />
  )
}

Component Requirements

When using the JSX Renderer, you need to provide all components that are referenced in your JSX string. For example:

const components = {
  Button,
  Card,
  Input,
  // ... any other components you want to use
}
 
const jsxString = `
  <Card className="p-4">
    <h2 className="text-lg font-semibold">Hello World</h2>
    <Button>Click me</Button>
  </Card>
`
 
<JsxRenderer jsx={jsxString} components={components} />

Examples

Streaming State

Disabled State

Error Handling

The component includes an error boundary to catch rendering errors:

<JsxRenderer
  jsx={jsxString}
  onError={(error, errorInfo) => console.error(error)}
  fallback={CustomFallback}
/>

API Reference

PropTypeDefaultDescription
jsxstring-The JSX string to render
fixIncompleteJsxbooleantrueWhether to automatically complete unclosed JSX tags
componentsRecord<string, React.ComponentType>-Map of component names to their React components
state"disabled" | "read-only" | "interactive" | "streaming" | "error""interactive"The state of the renderer affecting styling and behavior
fallbackReact.ComponentTypeErrorFallbackCustom fallback component for error boundary
onError(error: Error, errorInfo: React.ErrorInfo) => void-Callback for error handling