@worktual/react-native-ai-bot
v1.3.0
Published
Drop-in AI chatbot for React Native apps. Preloads silently in the background, opens instantly with zero loading screen.
Maintainers
Readme
@worktual/react-native-ai-bot
Drop-in AI chatbot for React Native apps. Preloads silently in the background — opens instantly with zero loading screen.
- ✅ Zero loading screen — bot is fully loaded before user taps
- ✅ Survives navigation, tabs, and re-renders
- ✅ Built-in error handling with retry
- ✅ Android back-button support
- ✅ Fully customizable branding
- ✅ TypeScript-first with full type definitions
Installation
npm install @worktual/react-native-ai-bot react-native-webview react-native-safe-area-contextFor iOS:
cd ios && pod installQuick Start (2 Steps)
Step 1 — Wrap your app once with WorktualAIBotProvider
In your root App.tsx:
import React from "react";
import { SafeAreaProvider } from "react-native-safe-area-context";
import { WorktualAIBotProvider } from "@worktual/react-native-ai-bot";
const App = () => (
<SafeAreaProvider>
<WorktualAIBotProvider webchatId="YOUR_WEBCHAT_ID">
{/* Your app — navigators, screens, etc. */}
<AppNavigator />
</WorktualAIBotProvider>
</SafeAreaProvider>
);
export default App;The bot WebView mounts silently in the background as soon as your app starts. By the time the user taps the chat button, it's already fully loaded.
Step 2 — Show / hide from anywhere via useWorktualAIBot
import { TouchableOpacity, Text } from "react-native";
import { useWorktualAIBot } from "@worktual/react-native-ai-bot";
const HomeScreen = () => {
const { show } = useWorktualAIBot();
return (
<TouchableOpacity onPress={show}>
<Text>Open AI Chat</Text>
</TouchableOpacity>
);
};That's it. The bot opens instantly — no loading screen, no delay. The bot closes itself automatically when the user taps the close button inside the chat, or when the user presses the Android back button.
How It Works
WorktualAIBotProvidermounts the bot WebView once, hidden (opacity: 0, zIndex: -1)- The WebView loads bot HTML/JS/CSS silently while the user uses your app
- When the user taps your chat button,
show()flipsopacity: 1, zIndex: 9999 - The bot is already fully loaded → instant reveal, zero loading screen
- After close, the bot stays alive in memory → next open is instant too
useWorktualAIBot() API
const {
show,
hide,
reload,
sendMessage,
addMessageListener,
lastMessage,
isVisible,
isReady,
error,
} = useWorktualAIBot();| Returns | Type | Description |
|---|---|---|
| show | () => void | Show the bot instantly |
| hide | () => void | Hide the bot (WebView stays alive) |
| reload | () => void | Force-reload the bot (clears errors, remounts WebView) |
| sendMessage | (data) => void | Send a message from the app to the bot |
| addMessageListener | (fn) => unsub | Subscribe to messages from the bot; returns unsubscribe |
| lastMessage | WorktualAIBotMessage \| null | The most recent message from the bot (reactive) |
| isVisible | boolean | Whether the bot is currently visible |
| isReady | boolean | Whether the WebView has finished its initial load |
| error | WorktualAIBotError \| null | Current error, if any (auto-cleared on next successful load) |
Two-Way Messaging Between App and Bot
The SDK supports bidirectional communication — your app can listen for events from the bot, and you can also send messages from your app to the bot.
1. Bot → App (listen for events from the bot)
You have three ways to consume messages from the bot — pick whichever fits best:
Option A — onMessage prop on the Provider (global, app-wide):
<WorktualAIBotProvider
webchatId="YOUR_WEBCHAT_ID"
onMessage={(data) => {
if (data.type === "user_started_chat") {
analytics.track("Chat Started", { sessionId: data.sessionId });
}
if (data.type === "agent_handoff") {
navigation.navigate("AgentScreen", { agentId: data.agentId });
}
}}
>
<AppNavigator />
</WorktualAIBotProvider>Option B — addMessageListener on the hook (component-level subscriptions):
import { useEffect } from "react";
import { useWorktualAIBot } from "@worktual/react-native-ai-bot";
const SupportScreen = () => {
const { addMessageListener } = useWorktualAIBot();
useEffect(() => {
const unsubscribe = addMessageListener((data) => {
if (typeof data === "object" && data.type === "feedback_submitted") {
Toast.show("Thanks for your feedback!");
}
});
return unsubscribe; // auto-cleanup on unmount
}, [addMessageListener]);
return <View />;
};Multiple components can subscribe independently — they all receive every message.
Option C — lastMessage reactive state (good for displaying latest event):
const { lastMessage } = useWorktualAIBot();
useEffect(() => {
if (lastMessage && typeof lastMessage === "object") {
console.log("[Bot →]", lastMessage);
}
}, [lastMessage]);The bot HTML sends messages via:
window.ReactNativeWebView.postMessage(
JSON.stringify({ type: "user_started_chat", sessionId: "abc123" })
);Note: Non-JSON messages (raw strings) are also forwarded — you'll receive them as
stringinstead ofobject. The TypeScript typeWorktualAIBotMessagereflects this:Record<string, unknown> | string.
Built-in events the SDK already handles for you
| Event type | Triggered by | What the SDK does |
|---|---|---|
| webchat_ready | Bot finished loading | Hides the fallback loader, calls onReady |
| webchat_end | User taps close inside the bot | Auto-hides the bot, calls onClose |
You can still observe these via onMessage if you want.
2. App → Bot (send messages from your app)
Call sendMessage(data) from the hook to push data into the bot WebView at any time:
import { useWorktualAIBot } from "@worktual/react-native-ai-bot";
const ProfileScreen = () => {
const { sendMessage, show } = useWorktualAIBot();
const openChatWithUser = () => {
// Send user context FIRST, then show the bot
sendMessage({
type: "auth",
userId: "12345",
name: "John Doe",
email: "[email protected]",
});
show();
};
return <Button title="Talk to support" onPress={openChatWithUser} />;
};The bot HTML can receive these messages two ways:
Option A — Define a global handler (simplest):
// Inside your bot HTML (e.g. ailivebot.html)
window.onWorktualMessage = function (data) {
console.log("[App →]", data);
if (data.type === "auth") {
setCurrentUser(data.userId, data.name);
}
};Option B — Use the CustomEvent listener:
window.addEventListener("worktual:message", function (e) {
const data = e.detail;
console.log("[App →]", data);
});End-to-end example
// App.tsx
<WorktualAIBotProvider
webchatId="YOUR_WEBCHAT_ID"
onMessage={(data) => {
if (data.type === "feedback_submitted") {
Toast.show("Thanks for your feedback!");
}
}}
>
<AppNavigator />
</WorktualAIBotProvider>
// AnyScreen.tsx
const { sendMessage, show } = useWorktualAIBot();
const startSupport = () => {
sendMessage({
type: "context",
page: "checkout",
cartTotal: 99.99,
locale: "en-GB",
});
show();
};Provider Props
| Prop | Type | Default | Description |
|---|---|---|---|
| webchatId | string | Required | Your webchat ID from Worktual |
| baseUrl | string | Production URL | Custom bot URL if self-hosted |
| statusBarColor | string | "#C62828" | Background colour behind status bar |
| primaryColor | string | "#575CFF" | Spinner / button colour |
| loadingBackground | string | "#f8f9fb" | Fallback loader background |
| loadingLogo | ImageSourcePropType | Spinner | Logo on fallback loader |
| loadingTitle | string | "AI Assistant" | Fallback loader title |
| loadingSubtitle | string | "Loading your chat..." | Fallback loader subtitle |
| errorMessage | string | "Couldn't load chat..." | Error UI message |
| retryButtonText | string | "Try Again" | Retry button label |
| maxLoadTime | number | 6000 | Max ms to wait before force-revealing chat |
| onReady | () => void | — | Called when chat is fully loaded |
| onClose | () => void | — | Called when bot is closed |
| onError | (error) => void | — | Called when the WebView fails to load |
| onMessage | (data) => void | — | Called on every message from chat |
Error Handling
If the WebView fails to load (offline, server error, etc.), the SDK shows a built-in error screen with a retry button. You can also handle errors yourself:
<WorktualAIBotProvider
webchatId="YOUR_WEBCHAT_ID"
onError={(error) => {
console.warn("[Bot]", error.type, error.message);
// Optional: log to Sentry / Firebase Crashlytics
}}
>
<AppNavigator />
</WorktualAIBotProvider>The error object:
interface WorktualAIBotError {
type: "network" | "http" | "unknown";
message: string;
statusCode?: number;
url?: string;
}Programmatic retry:
const { reload, error } = useWorktualAIBot();
if (error) {
return <Button title="Retry" onPress={reload} />;
}Custom Branding
<WorktualAIBotProvider
webchatId="YOUR_WEBCHAT_ID"
statusBarColor="#FF6B00"
primaryColor="#FF6B00"
loadingLogo={require("./assets/logo.png")}
loadingTitle="Support Chat"
loadingBackground="#FFF8F0"
>
<AppNavigator />
</WorktualAIBotProvider>TypeScript
The package is written in TypeScript and ships full type definitions:
import type {
WorktualAIBotManagerConfig,
WorktualAIBotContextValue,
WorktualAIBotError,
} from "@worktual/react-native-ai-bot";Troubleshooting
"useWorktualAIBot() was called outside of <WorktualAIBotProvider>"
You forgot to wrap your app with <WorktualAIBotProvider> in App.tsx. The Provider must wrap any component that uses the hook.
Bot is blank / never opens
- Check that you have an active internet connection on the device
- Verify your
webchatIdis correct (contact your Worktual account manager) - Check the
errorstate from the hook — the SDK surfaces network/HTTP failures
Bot opens but shows the loading screen briefly
This means the user tapped the chat button before the WebView finished its initial load (cold-start + slow network). Once it finishes, every subsequent open is instant. Adjust maxLoadTime if needed.
iOS Pod install fails
Run cd ios && pod install --repo-update to refresh CocoaPods specs.
Status bar covers the bot header on Android
Make sure your activity uses a theme that doesn't draw behind the status bar, or use statusBarColor prop to match your theme.
Legacy <WorktualAIBot /> Component
The standalone <WorktualAIBot /> component is still exported for backward compatibility, but the WorktualAIBotProvider + useWorktualAIBot pattern is strongly recommended — it's the only way to get true zero-loading-screen instant open.
Requirements
- React Native >= 0.65
- React >= 17
react-native-webview>= 11react-native-safe-area-context>= 4- iOS 13+ / Android 5+ (API 21+)
License
MIT — see LICENSE.
Support
Contact your Worktual account manager for your webchatId and integration support.
