What’s This About?
Want to build your own custom chat UI? We provide React hooks and components that make it easy to:
- Create custom chat interfaces
- Manage chat state
- Handle messages and responses
- Build your own UI components
Basic Setup
First, wrap your app with our WidgetRoot
provider:
import { WidgetRoot } from "@openchatai/widget";
function App() {
return (
<WidgetRoot
options={{
token: 'your-token',
initialMessage: 'Welcome!',
}}
>
<YourCustomChat />
</WidgetRoot>
);
}
Available Options
type WidgetOptions = {
token: string,
initialMessage?: string[],
apiUrl?: string,
socketUrl?: string,
defaultOpen?: boolean,
debug?: boolean,
organizationName?: string,
headers?: Record<string, string>,
onClose?: () => void,
onHandoff?: (data: HandoffData) => void,
user?: {
name?: string,
email?: string,
phone?: string,
avatarUrl?: string,
customData?: Record<string, string>,
},
bot?: {
name?: string,
avatarUrl?: string,
},
components?: {
key: string,
component: React.ElementType
}[]
}
Useful Hooks
1. useChat Hook
The main hook for chat functionality:
import { useChat } from "@openchatai/widget";
function CustomChat() {
const {
sendMessage,
state,
clearSession,
recreateSession,
} = useChat();
return (
<div>
{state.messages.map((msg) => (
<div key={msg.id}>{msg.content}</div>
))}
<button onClick={() => sendMessage("Hello!")}>
Send Message
</button>
</div>
);
}
2. useConfigData Hook
Access your widget configuration:
import { useConfigData } from "@openchatai/widget";
function ChatHeader() {
const config = useConfigData();
return (
<header>
Welcome to {config.organizationName}!
</header>
);
}
3. Message Rating Hooks
Add thumbs up/down to messages:
import { useUpvote, useDownvote } from "@openchatai/widget";
function MessageRating({ messageId }) {
const [upvoteState, upvote] = useUpvote(messageId);
const [downvoteState, downvote] = useDownvote(messageId);
return (
<div>
<button onClick={upvote}>👍</button>
<button onClick={downvote}>👎</button>
</div>
);
}
Custom Message Components
You can create custom components for different message types:
import { BotMessage, ComponentProps } from "@openchatai/widget";
function WeatherDisplay({ data }: ComponentProps<WeatherData>) {
return (
<div>
<h3>Current Weather</h3>
<p>{data.temperature}°C</p>
</div>
);
}
function ChatMessages() {
const { state } = useChat();
return (
<div>
{state.messages.map((message, i) => (
message.type === "FROM_BOT" ? (
<BotMessage
message={message}
index={i}
key={i}
/>
) : (
<UserMessage message={message} key={i} />
)
))}
</div>
);
}
Remember to:
- Always wrap your app with
WidgetRoot
- Handle loading and error states
- Consider mobile responsiveness
Need help? Check out our example repo or join our Slack community!