@mahekchaniyara/react-native-chatbubble-sdk
v1.0.4
Published
A comprehensive React Native ChatBot SDK with customizable UI components and easy integration
Maintainers
Readme
React Native ChatBubble SDK
A comprehensive and customizable React Native ChatBot SDK that provides an easy-to-integrate chat interface with powerful features and flexible theming options.
Features
- 🎨 Fully Customizable UI - Themes, colors, fonts, and layouts
- 💬 Real-time Messaging - Smooth chat experience with typing indicators
- 📱 Cross-platform - Works on both iOS and Android
- 🔄 Message Persistence - Optional message history storage
- 🎯 TypeScript Support - Full type safety and IntelliSense
- 🔌 Easy Integration - Simple setup with minimal configuration
- 🎭 Multiple Themes - Light, dark, and custom theme presets
- 📊 Event System - Listen to chat events and customize behavior
- 🔧 Configurable Features - Enable/disable features as needed
Installation
npm install react-native-chatbubble-sdk
# or
yarn add react-native-chatbubble-sdkDependencies
This SDK requires the following peer dependencies:
npm install @react-native-async-storage/async-storage
# or
yarn add @react-native-async-storage/async-storageQuick Start
1. Basic Setup
import React from 'react';
import { View } from 'react-native';
import { ChatBubble, ChatBotProvider, createConfig } from 'react-native-chatbubble-sdk';
const config = createConfig()
.setApiKey('your-api-key-here')
.setWelcomeMessage('Hello! How can I help you today?')
.build();
export default function App() {
return (
<ChatBotProvider config={config}>
<View style={{ flex: 1 }}>
{/* Your app content */}
<ChatBubble />
</View>
</ChatBotProvider>
);
}2. Advanced Configuration
import { createConfig, themePresets } from 'react-native-chatbubble-sdk';
const config = createConfig()
.setApiKey('your-api-key-here')
.setBaseUrl('https://your-api-endpoint.com')
.setTheme(themePresets.dark)
.setPrimaryColor('#FF6B6B')
.enableTyping(true)
.enablePersistence(true)
.enableTimestamps(true)
.setWelcomeMessage('Welcome to our support chat!')
.setPlaceholder('Ask me anything...')
.build();Configuration Options
Theme Configuration
const customTheme = {
primaryColor: '#007AFF',
secondaryColor: '#E5E5EA',
backgroundColor: '#FFFFFF',
textColor: '#000000',
bubbleColor: {
user: '#007AFF',
bot: '#E5E5EA',
},
borderRadius: 18,
fontSize: 16,
};
const config = createConfig()
.setApiKey('your-api-key')
.setTheme(customTheme)
.build();Feature Configuration
const config = createConfig()
.setApiKey('your-api-key')
.enableTyping(true) // Show typing indicators
.enablePersistence(true) // Save message history
.enableFileUpload(false) // Allow file uploads
.enableQuickReplies(true) // Show quick reply buttons
.enableTimestamps(false) // Show message timestamps
.enableAvatars(true) // Show user/bot avatars
.build();API Reference
Components
<ChatBubble />
The main chat interface component.
Props:
config?: Partial<ChatBotConfig>- Override provider configurationonMessageSent?: (message: string) => void- Callback when user sends a messageonMessageReceived?: (message: ChatMessage) => void- Callback when bot respondsstyle?: ViewStyle- Custom styling for the chat bubble
<ChatBotProvider />
Context provider that manages chat state and configuration.
Props:
config: ChatBotConfig- Chat configuration objectchildren: ReactNode- Child components
Hooks
useChatBot()
Hook to access chat functionality and state.
const {
messages,
sendMessage,
clearHistory,
isTyping,
isConnected,
config,
addEventListener,
} = useChatBot();Configuration Builder
createConfig()
Fluent API for building chat configuration.
const config = createConfig()
.setApiKey(string)
.setBaseUrl(string)
.setTheme(ChatTheme)
.setFeatures(ChatFeatures)
.setCustomization(ChatCustomization)
.setPrimaryColor(string)
.enableDarkTheme()
.enableLightTheme()
.enableTyping(boolean)
.enablePersistence(boolean)
.setWelcomeMessage(string)
.setPlaceholder(string)
.build();Event System
Listen to chat events for custom behavior:
import { useChatBot } from 'react-native-chatbubble-sdk';
function MyComponent() {
const { addEventListener } = useChatBot();
useEffect(() => {
const unsubscribe = addEventListener((event) => {
switch (event.type) {
case 'message_sent':
console.log('User sent:', event.payload);
break;
case 'message_received':
console.log('Bot replied:', event.payload);
break;
case 'typing_start':
console.log('Bot is typing...');
break;
case 'error':
console.error('Chat error:', event.payload);
break;
}
});
return unsubscribe;
}, []);
return null;
}Theme Presets
The SDK includes several built-in theme presets:
import { themePresets } from 'react-native-chatbubble-sdk';
// Available presets:
// - themePresets.default
// - themePresets.dark
// - themePresets.minimal
// - themePresets.colorful
const config = createConfig()
.setApiKey('your-api-key')
.setTheme(themePresets.dark)
.build();API Integration
Setting up your ChatBot API
The SDK expects your API to handle POST requests to /chat endpoint:
// Expected request format
{
"message": "Hello",
"context": {},
"sessionId": "session-123"
}
// Expected response format
{
"message": "Hi there! How can I help you?",
"quickReplies": ["Option 1", "Option 2"],
"metadata": {}
}Custom API Integration
import { ChatBotService } from 'react-native-chatbubble-sdk';
const customService = new ChatBotService({
apiKey: 'your-api-key',
baseUrl: 'https://your-custom-api.com',
// ... other config
});
// Use the service directly
const response = await customService.sendMessage('Hello');Examples
Basic Chat Implementation
import React from 'react';
import { SafeAreaView, StyleSheet } from 'react-native';
import { ChatBubble, ChatBotProvider, createConfig } from 'react-native-chatbubble-sdk';
const config = createConfig()
.setApiKey(process.env.CHATBOT_API_KEY)
.setWelcomeMessage('Welcome! How can I assist you today?')
.enableTyping(true)
.build();
export default function ChatScreen() {
return (
<ChatBotProvider config={config}>
<SafeAreaView style={styles.container}>
<ChatBubble style={styles.chatBubble} />
</SafeAreaView>
</ChatBotProvider>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#f5f5f5',
},
chatBubble: {
position: 'absolute',
bottom: 20,
right: 20,
},
});Custom Themed Chat
import React from 'react';
import { createConfig } from 'react-native-chatbubble-sdk';
const darkConfig = createConfig()
.setApiKey('your-api-key')
.enableDarkTheme()
.setPrimaryColor('#BB86FC')
.setCustomization({
welcomeMessage: '🌙 Night mode activated! How can I help?',
placeholder: 'Type in the darkness...',
showTimestamp: true,
showAvatar: true,
})
.build();Event Handling Example
import React, { useEffect } from 'react';
import { useChatBot } from 'react-native-chatbubble-sdk';
function ChatEventHandler() {
const { addEventListener } = useChatBot();
useEffect(() => {
const unsubscribe = addEventListener((event) => {
switch (event.type) {
case 'message_sent':
// Track user messages
analytics.track('chat_message_sent', {
message: event.payload.text,
timestamp: event.timestamp,
});
break;
case 'message_received':
// Handle bot responses
if (event.payload.metadata?.action) {
handleBotAction(event.payload.metadata.action);
}
break;
case 'error':
// Handle errors
console.error('Chat error:', event.payload.error);
showErrorToast('Chat service unavailable');
break;
}
});
return unsubscribe;
}, []);
return null;
}Troubleshooting
Common Issues
AsyncStorage not found
npm install @react-native-async-storage/async-storageTypeScript errors
- Ensure you have TypeScript 4.8+ installed
- Check that all peer dependencies are installed
API connection issues
- Verify your API key is correct
- Check that your API endpoint is accessible
- Ensure CORS is configured for React Native requests
Performance Tips
- Enable message persistence only if needed
- Use throttling for rapid message sending
- Implement proper error boundaries
- Consider message pagination for long conversations
Contributing
We welcome contributions! Please see our Contributing Guide for details.
License
MIT License - see LICENSE file for details.
Support
- 📧 Email: [email protected]
- 🐛 Issues: GitHub Issues
- 📖 Documentation: Full API Docs
Changelog
See CHANGELOG.md for version history and updates.
