@m0rphic/jsx-render
v0.1.2
Published
Dynamic JSX rendering with Tailwind CSS - render AI-generated UI safely
Downloads
313
Maintainers
Readme
@m0rphic/jsx-render
Dynamic JSX generation with Claude AI and Tailwind CSS. Generate personalized, adaptive UI components based on user behavior.
Features
- AI-Powered UI Generation: Use Claude to generate React components dynamically
- Tailwind CSS Styling: Full support for Tailwind utility classes
- Behavior-Based Personalization: Track user behavior and generate personalized UIs
- Safe Rendering: Secure JSX rendering with validation and sanitization
- React Hooks & Components: Easy-to-use React integration
- TypeScript First: Full type safety throughout
Installation
npm install @m0rphic/jsx-render
# or
pnpm add @m0rphic/jsx-render
# or
yarn add @m0rphic/jsx-renderQuick Start
1. Basic Usage
import { generateUI, renderJSX } from '@m0rphic/jsx-render';
// Generate UI with Claude
const result = await generateUI('Create a login form with email and password fields');
// Render to React
const LoginForm = () => {
const handlers = {
handleSubmit: (e) => {
e.preventDefault();
console.log('Form submitted');
},
};
return renderJSX(result.ui, { handlers });
};2. React Integration
import {
AdaptiveUIProvider,
GeneratedUI,
} from '@m0rphic/jsx-render/react';
function App() {
const handlers = {
handleLogin: () => console.log('Login clicked'),
handleSignup: () => console.log('Signup clicked'),
};
return (
<AdaptiveUIProvider
userId="user-123"
handlers={handlers}
enableTracking={true}
>
<GeneratedUI
prompt="Create a hero section for a crypto wallet app"
personalized={true}
cacheKey="hero-section"
/>
</AdaptiveUIProvider>
);
}3. With Behavior Tracking
import {
useBehaviorTracking,
useGeneratedUI,
} from '@m0rphic/jsx-render/react';
function Dashboard() {
const { profile, trackFeature } = useBehaviorTracking({
userId: 'user-123',
autoTrack: true,
});
const { ui, isLoading } = useGeneratedUI({
prompt: 'Create a dashboard with quick actions',
userBehavior: profile,
});
if (isLoading) return <div>Loading...</div>;
return <div onClick={() => trackFeature('dashboard-view')}>{ui}</div>;
}Core Concepts
JSX Element Structure
The SDK uses a structured JSON format to represent JSX elements:
interface JSXElement {
tag: string; // HTML tag or component name
className?: string; // Tailwind CSS classes
props?: object; // HTML/React props
handlers?: object; // Event handler references
children?: JSXChildren; // Nested elements or text
}Example:
{
"tag": "div",
"className": "flex flex-col gap-4 p-6 bg-white rounded-xl shadow-lg",
"children": [
{
"tag": "h1",
"className": "text-2xl font-bold text-gray-900",
"children": "Welcome"
},
{
"tag": "button",
"className": "px-4 py-2 bg-blue-500 text-white rounded-lg",
"handlers": { "onClick": "handleClick" },
"children": "Get Started"
}
]
}Security
The renderer includes multiple security layers:
- Tag Whitelist: Only allowed HTML tags can be rendered
- Prop Blacklist: Dangerous props like
dangerouslySetInnerHTMLare blocked - Class Validation: Tailwind classes are validated against patterns
- Handler References: Event handlers are referenced by name, not code
User Behavior Profile
Track and use behavior data for personalization:
interface UserBehaviorProfile {
userId: string;
preferences: {
colorScheme: 'light' | 'dark' | 'system';
fontSize: 'small' | 'medium' | 'large';
reducedMotion: boolean;
locale: string;
};
patterns: {
primaryDevice: 'mobile' | 'tablet' | 'desktop';
navigationStyle: 'keyboard' | 'mouse' | 'touch';
avgSessionDuration: number;
};
featureUsage: {
topFeatures: Array<{ featureId: string; usageCount: number }>;
};
}API Reference
Core Functions
generateUI(prompt, userBehavior?, options?)
Generate UI using Claude.
const result = await generateUI(
'Create a settings panel',
userBehavior,
{ model: 'claude-sonnet-4-20250514' }
);renderJSX(element, options?)
Render a JSX element structure to React.
const reactElement = renderJSX(jsxElement, {
handlers: { handleClick: () => {} },
components: { CustomCard: MyCardComponent },
});validateElement(element, options?)
Validate a JSX element structure.
const result = validateElement(jsxElement);
if (!result.valid) {
console.error(result.errors);
}React Hooks
useGeneratedUI(options)
Hook for generating and rendering UI.
const { ui, isLoading, error, regenerate, refine } = useGeneratedUI({
prompt: 'Create a form',
userBehavior: profile,
cacheKey: 'my-form',
});useBehaviorTracking(options)
Hook for tracking user behavior.
const { profile, trackFeature, trackClick, updatePreferences } = useBehaviorTracking({
userId: 'user-123',
autoTrack: true,
});React Components
<AdaptiveUIProvider>
Context provider for adaptive UI.
<AdaptiveUIProvider
userId="user-123"
handlers={handlers}
components={components}
enableTracking={true}
>
{children}
</AdaptiveUIProvider><GeneratedUI>
Component that renders AI-generated UI.
<GeneratedUI
prompt="Create a navbar"
personalized={true}
loading={<Skeleton />}
error={(e) => <Error message={e.message} />}
fallback={<DefaultNavbar />}
/><JSXRenderer>
Component that renders a JSX element structure.
<JSXRenderer
element={jsxElement}
handlers={handlers}
validateClasses={true}
/><Tracked>
Wrapper for tracking interactions.
<Tracked featureId="signup-button" trackClicks={true}>
<button>Sign Up</button>
</Tracked>Tool Schema
The SDK provides a Claude Tool schema for UI generation:
import { generateUITool, getTools } from '@m0rphic/jsx-render';
// Use in Claude API calls
const response = await anthropic.messages.create({
model: 'claude-sonnet-4-20250514',
tools: [generateUITool],
tool_choice: { type: 'tool', name: 'generate_ui' },
messages: [{ role: 'user', content: 'Create a button' }],
});Design System Integration
Configure your design system:
const designSystem = {
colors: {
primary: 'blue-500',
secondary: 'gray-500',
accent: 'purple-500',
},
borderRadius: 'lg',
typography: {
fontFamily: 'Inter',
headingWeight: 'bold',
},
};
await generateUI('Create a card', undefined, { designSystem });Examples
See the examples directory for complete usage examples:
- Basic generation
- React integration
- Behavior tracking
- A/B testing variants
- Design system usage
Environment Variables
ANTHROPIC_API_KEY=your-api-keyLicense
MIT
