chatflows-embed
v1.1.9
Published
React package for ChatFlows embed widget
Readme
ChatFlows React Embed
Add AI-powered chat to your React app in minutes. The ChatFlows embed package provides a simple, production-ready way to integrate ChatFlows into any React application.
Features
- ✨ Simple Setup - Get started with 3 lines of code
- 🎯 Type-Safe - Full TypeScript support with complete type definitions
- 🚀 Zero Config - Works out of the box with sensible defaults
- 🔌 Custom Functions - Let AI call your functions
- 📱 Responsive - Works on desktop and mobile
- 🎨 Customizable - Position, colors, and behavior
- ⚡ Performance - Async loading, no render blocking
- 🔒 Secure - User context and session management
Installation
npm install @addai/embedQuick Start
import { ChatflowsProvider, Embed } from '@addai/embed';
function App() {
return (
<ChatflowsProvider>
<Embed publicKey="your-public-key-here" />
<YourApp />
</ChatflowsProvider>
);
}That's it! The chat widget will appear in the bottom-right corner of your app.
Basic Usage
1. Wrap Your App
import { ChatflowsProvider, Embed } from '@addai/embed';
function App() {
return (
<ChatflowsProvider>
{/* Initialize the widget */}
<Embed publicKey="your-key" />
{/* Your app */}
<YourComponents />
</ChatflowsProvider>
);
}2. Control the Widget
import { useChatflows } from '@addai/embed';
function ChatButton() {
const { open, close, toggle, isOpen, isReady } = useChatflows();
return (
<button onClick={open} disabled={!isReady}>
{isOpen ? 'Close Chat' : 'Open Chat'}
</button>
);
}3. Register Custom Functions
import { useChatflows } from '@addai/embed';
import { useEffect } from 'react';
function Dashboard() {
const { registerFunction } = useChatflows();
useEffect(() => {
// Let AI call this function
registerFunction('getAccountBalance', async () => {
const balance = await fetchBalance();
return { balance };
});
}, [registerFunction]);
return <div>Dashboard</div>;
}4. Update User Context
import { useChatflows } from '@addai/embed';
function LoginButton() {
const { updateContext } = useChatflows();
const handleLogin = async (user) => {
await updateContext({
id: user.id,
name: user.name,
email: user.email
});
};
return <button onClick={handleLogin}>Login</button>;
}Configuration
Embed Props
<Embed
publicKey="your-key" // Required
apiUrl="https://chatflows.add.ai" // Optional
position="bottom-right" // Optional: bottom-right, bottom-left, top-right, top-left
draggable={true} // Optional: Allow button dragging
offsetX="20px" // Optional: Horizontal offset
offsetY="20px" // Optional: Vertical offset
buttonSize="60px" // Optional: Button size
user={{ // Optional: Initial user data
id: '123',
name: 'John',
email: '[email protected]'
}}
onReady={() => console.log('Ready!')} // Optional
onError={(error) => console.error(error)} // Optional
/>API
useChatflows() Hook
Returns an object with:
open()- Open the chat widgetclose()- Close the chat widgettoggle()- Toggle widget open/closedregisterFunction(name, callback)- Register a function AI can callupdateContext(data)- Update user contextclearSession()- Clear current sessionisOpen- Boolean indicating if widget is openisReady- Boolean indicating if widget is initialized
Examples
Complete App Example
import { ChatflowsProvider, Embed, useChatflows } from '@addai/embed';
import { useEffect, useState } from 'react';
function ChatControls() {
const {
open,
close,
registerFunction,
updateContext,
isReady,
isOpen
} = useChatflows();
// Register custom functions
useEffect(() => {
if (!isReady) return;
registerFunction('getUser', async () => ({
name: 'John Doe',
email: '[email protected]',
plan: 'Premium'
}));
registerFunction('createTicket', async (parameters) => {
const ticket = await createSupportTicket(parameters);
return {
ticketId: ticket.id,
message: 'Ticket created successfully!'
};
});
}, [registerFunction, isReady]);
const handleLogin = async () => {
await updateContext({
id: '123',
name: 'John Doe',
email: '[email protected]'
});
};
return (
<div>
<button onClick={open} disabled={!isReady}>
Open Chat
</button>
<button onClick={close}>Close Chat</button>
<button onClick={handleLogin}>Login</button>
<p>Status: {isOpen ? 'Open' : 'Closed'}</p>
</div>
);
}
function App() {
return (
<ChatflowsProvider>
<Embed publicKey="your-public-key" />
<ChatControls />
</ChatflowsProvider>
);
}
export default App;Register Multiple Functions
function ProductPage() {
const { registerFunction } = useChatflows();
useEffect(() => {
// Get product info
registerFunction('getProduct', async (parameters) => {
const product = await fetchProduct(parameters.productId);
return {
name: product.name,
price: product.price,
inStock: product.stock > 0
};
});
// Add to cart
registerFunction('addToCart', async (parameters) => {
await addToCart(parameters.productId, parameters.quantity);
return {
success: true,
message: 'Added to cart!'
};
});
// Check order status
registerFunction('getOrderStatus', async (parameters) => {
const order = await fetchOrder(parameters.orderId);
return {
status: order.status,
tracking: order.trackingNumber,
estimatedDelivery: order.deliveryDate
};
});
}, [registerFunction]);
return <div>Product Page</div>;
}Dynamic User Updates
function App() {
const user = useAuth(); // Your auth hook
const { updateContext, isReady } = useChatflows();
// Update chat when user changes
useEffect(() => {
if (isReady && user) {
updateContext({
id: user.id,
name: user.name,
email: user.email,
subscription: user.plan
});
}
}, [user, isReady, updateContext]);
return <div>Your app</div>;
}Logout Handler
function LogoutButton() {
const { clearSession } = useChatflows();
const handleLogout = () => {
clearSession(); // Clear chat session
logout(); // Your logout logic
};
return <button onClick={handleLogout}>Logout</button>;
}Documentation
- Quick Start - Get started in 5 minutes
- API Reference - Complete API documentation
- Troubleshooting - Common issues and solutions
- Examples - Working code examples
TypeScript
Full TypeScript support included:
import type {
EmbedConfig,
UserData,
ChatflowsContextType
} from '@addai/embed';Browser Support
- Chrome (latest)
- Firefox (latest)
- Safari (latest)
- Edge (latest)
- Mobile browsers (iOS Safari, Chrome Android)
Requirements
- React >= 16.8.0 (Hooks support)
- React DOM >= 16.8.0
FAQ
Does this work with Next.js?
Yes! Works with Next.js App Router and Pages Router.
Does this work with Create React App?
Yes! Works out of the box.
Does this work with Vite?
Yes! Fully compatible.
Does this work with React Native?
No, this is for web only. Contact us for React Native support.
How do I customize the widget appearance?
Widget appearance is controlled from your ChatFlows dashboard. The embed package handles integration only.
Can I have multiple chat widgets?
Not recommended. Use one widget per page with different user contexts.
Does this affect my app's performance?
No. The widget loads asynchronously and doesn't block your app's rendering.
License
MIT
Support
Contributing
We welcome contributions! Please see our contributing guidelines.
Made with ❤️ by the ChatFlows team
