Getting started: Chat with React Native
This guide will get you started with Ably Chat on a new React Native application.
It will take you through the following steps:
- Creating a client and establishing a realtime connection to Ably
- Creating a room and subscribing to its messages
- Sending messages to the room and editing messages
- Retrieving historical messages to provide context for new joiners
- Setting up typing indicators to see which clients are typing
- Use presence to display the online status of users in the room
- Subscribing to and sending reactions
- Disconnecting and resource cleanup
Prerequisites
Ably
-
Sign up for an Ably account
-
Create a new app and get your API key. You can use the root API key that is provided by default to get started.
-
Install the Ably CLI:
npm install -g @ably/cli
- Run the following to log in to your Ably account and set the default app and API key:
ably login
ably apps switch
ably auth keys switch
Create a new project
- Create a new React Native project using the React Native CLI. For detailed instructions, refer to the React Native documentation.
npx rn-new@latest my-chat-react-native-app --nativewind
cd my-chat-react-native-app
- Install the Ably Chat SDK and its dependencies:
npm install @ably/chat ably
- For iOS, install the native dependencies:
cd ios && pod install && cd ..
Step 1: Setting up the Ably and Chat client providers
The Ably Pub/Sub SDK and the Ably Chat SDK expose React hooks and context providers to make it easier to use them in your React Native components. The AblyProvider
and ChatClientProvider
should be used at the top level of your application, typically in App.tsx
. These are required when working with the useChatConnection
hook and ChatRoomProvider
exposed by Ably Chat.
Replace the contents of your App.tsx
file with the following code to set up the providers:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// App.tsx
import React from 'react';
import * as Ably from 'ably';
import { ChatClient, LogLevel } from '@ably/chat';
import { ChatClientProvider } from '@ably/chat/react';
import { AblyProvider } from 'ably/react';
import './global.css';
// Create your Ably Realtime client and ChatClient instances:
const realtimeClient = new Ably.Realtime({
key: 'demokey:*****',
clientId: 'my-first-client',
});
const chatClient = new ChatClient(realtimeClient, {
logLevel: LogLevel.Info,
});
export default function App() {
return (
<AblyProvider client={realtimeClient}>
<ChatClientProvider client={chatClient}>
</ChatClientProvider>
</AblyProvider>
);
}
Step 2: Connect to Ably
Clients establish a connection with Ably when they instantiate an SDK. This enables them to send and receive messages in realtime across channels. This hook must be nested within a ChatClientProvider
.
Create a new file ChatApp.tsx
and add the following functions with the imports needed for the chat functionality:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// ChatApp.tsx
import React, {useCallback, useEffect, useState} from 'react';
import {
SafeAreaView,
ScrollView,
Text,
TextInput,
TouchableOpacity,
View,
StyleSheet,
KeyboardAvoidingView,
Platform,
Alert,
Modal
} from 'react-native';
import {
ChatRoomProvider,
useChatConnection,
useMessages,
usePresence,
usePresenceListener,
useRoom,
useRoomReactions,
useTyping,
} from '@ably/chat/react';
import {
ChatMessageEvent,
Message,
ChatMessageEventType,
RoomReaction,
} from '@ably/chat';
// This component will display the current connection status
function ConnectionStatus() {
const {currentStatus} = useChatConnection();
return (
<View className="p-4 h-full bg-gray-100">
<Text className="text-lg font-semibold text-blue-500">Ably Chat Connection</Text>
<Text className="mt-2">Connection: {currentStatus}!</Text>
</View>
);
}
function ChatApp() {
return (
<KeyboardAvoidingView
className="flex-1"
behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
keyboardVerticalOffset={0}>
<SafeAreaView className="flex-1 pt-10">
<View className="flex-1 w-full border border-blue-500 rounded-lg overflow-hidden">
<View className="flex-row h-24">
<View className="flex-1">
<ConnectionStatus />
</View>
<View className="flex-1">
{/* RoomStatus will be called here */}
</View>
</View>
<View className="flex-1 flex-row">
<View className="flex-1 bg-white">
{/* ChatBox component will be called here */}
</View>
</View>
</View>
</SafeAreaView>
</KeyboardAvoidingView>
);
}
export default ChatApp;
In the App.tsx
file, add the import for this new component:
1
import ChatApp from './ChatApp';
Update tailwind.config.js
content to include your ChatApp
following:
1
content: ['./App.{js,ts,tsx}', './ChatApp.{js,ts,tsx}', './components/**/*.{js,ts,tsx}'],
Now in your return()
within the <ChatCLientProvider></ChatClientProvider>
add your new ChatApp
component:
1
2
3
4
5
6
7
return (
<AblyProvider client={realtimeClient}>
<ChatClientProvider client={chatClient}>
<ChatApp />
</ChatClientProvider>
</AblyProvider>
);
Run your application by starting the development server and choose the method of running (Android, iPhone, Simulator):
npm run start
The application should now be running on either your device or simulator. You should see the connection status displayed with "Connection: connected!".
Step 3: Create a room
Now that you have a connection to Ably, you can create a room. Use rooms to separate and organize clients and messages into different topics, or 'chat rooms'. Rooms are the entry object into Chat, providing access to all of its features, such as messages, presence and reactions.
Ably Chat exposes the ChatRoomProvider
to help you create and manage rooms. It must be nested under the ChatClientProvider
described above.
This provider also gives you access to the room via the useRoom()
hook,
which you can be used to interact with the room and monitor its status.
In your project, open ChatApp.tsx
, and add a new component called RoomStatus
:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// ChatApp.tsx
// ...existing code...
function RoomStatus() {
const [currentRoomStatus, setCurrentRoomStatus] = useState('');
const {roomName} = useRoom({
onStatusChange: (status) => {
setCurrentRoomStatus(status.current);
},
});
return (
<View className="p-4 h-full bg-gray-100">
<Text className="text-lg font-semibold text-blue-500">Room Status</Text>
<Text className="mt-2">
Status: {currentRoomStatus}
{'\n'}
Room: {roomName}
</Text>
</View>
);
}
Update your ChatApp()
component first by wrapping the contents of the return with a ChatRoomProvider
, then find the line /* RoomStatus will be called here */
and replace it with <RoomStatus />
.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
function ChatApp() {
return (
<ChatRoomProvider name="my-first-room">
<KeyboardAvoidingView
className="flex-1"
behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
keyboardVerticalOffset={0}>
<SafeAreaView className="flex-1 pt-10">
<View className="flex-1 w-full border border-blue-500 rounded-lg overflow-hidden">
<View className="flex-row h-24">
<View className="flex-1">
<ConnectionStatus />
</View>
<View className="flex-1">
{/* Added RoomStatus component */}
<RoomStatus />
</View>
</View>
<View className="flex-1 flex-row">
<View className="flex-1 bg-white">
{/* ChatBox component will be called here */}
</View>
</View>
</View>
</SafeAreaView>
</KeyboardAvoidingView>
</ChatRoomProvider>
);
}
// ...existing code...
The above code creates a room with the name my-first-room
and sets up a listener to monitor the room status. It also displays the room name and current status in the UI.
Step 4: Send a message
Messages are how your clients interact with one another and Ably Chat exposes a useMessages()
hook to interact with the messages feature of the Chat SDK. After the room provider is set up, you can use the useMessages()
hook to send and receive messages in the room.
In ChatApp.tsx
, add a ChatBox
component which will allow users to send and receive messages:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// ChatApp.tsx
// ...existing code...
function ChatBox() {
const [inputValue, setInputValue] = useState('');
const [messages, setMessages] = useState<Message[]>([]);
const {sendMessage} = useMessages({
listener: (event: ChatMessageEvent) => {
const message = event.message;
switch (event.type) {
case ChatMessageEventType.Created: {
setMessages((prevMessages) => [...prevMessages, message]);
break;
}
default: {
console.error('Unhandled event', event);
}
}
},
});
const handleSend = () => {
if (!inputValue.trim()) return;
sendMessage({text: inputValue.trim()}).catch((err) =>
console.error('Error sending message', err),
);
setInputValue('');
};
return (
<View className="flex-1">
<ScrollView className="flex-1 p-4">
{messages.map((msg: Message) => {
const isMine = msg.clientId === 'my-first-client';
return (
<View
key={msg.serial}
className={`max-w-[60%] rounded-2xl px-3 py-2 shadow-sm mb-2 ${
isMine ? 'bg-green-200 text-gray-800 self-end rounded-br-none' : 'bg-blue-50 text-gray-800 self-start rounded-bl-none'
}`}>
<Text>{msg.text}</Text>
</View>
);
})}
</ScrollView>
<View className="flex flex-row items-center px-2 py-2 bg-white border-t border-gray-200">
<TextInput
className="flex-1 p-2 border border-gray-400 rounded outline-none bg-white"
placeholder="Type your message..."
value={inputValue}
onChangeText={setInputValue}
onSubmitEditing={handleSend}
/>
<TouchableOpacity
className="bg-blue-500 text-white px-4 ml-2 h-10 flex items-center justify-center rounded"
onPress={handleSend}>
<Text className="text-white font-semibold">Send</Text>
</TouchableOpacity>
</View>
</View>
);
}
Add ChatBox
component to your ChatApp
component:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Update ChatApp to include ChatBox
function ChatApp() {
return (
<ChatRoomProvider name="my-first-room">
<KeyboardAvoidingView
className="flex-1"
behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
keyboardVerticalOffset={0}>
<SafeAreaView className="flex-1 pt-10">
<View className="flex-1 w-full border border-blue-500 rounded-lg overflow-hidden">
<View className="flex-row h-24">
<View className="flex-1">
<ConnectionStatus />
</View>
<View className="flex-1">
<RoomStatus />
</View>
</View>
<View className="flex-1 flex-row">
<View className="flex-1 bg-white">
{/* Added ChatBox component */}
<ChatBox />
</View>
</View>
</View>
</SafeAreaView>
</KeyboardAvoidingView>
</ChatRoomProvider>
);
}
The UI will automatically render the new component, and you will be able to send messages to the room.
Type a message in the input box and click the send button. You'll see the message appear in the chat box.
You can also use the Ably CLI to send a message to the room from another environment:
ably rooms messages send my-first-room 'Hello from CLI!'
You'll see the message in your app's chat box UI. If you have sent a message via CLI, it should appear in a different color to the one you sent from the app.
Step 5: Edit a message
If your client makes a typo, or needs to update their original message then they can edit it. To do this, you can extend the functionality of the ChatBox
component to allow updating of messages. The useMessages()
hook exposes the updateMessage()
method of the Chat SDK messages feature.
Expose the updateMessage()
method from the useMessages()
hook and then add a method to the ChatBox
component to handle the edit action like so:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// ChatApp.tsx - Update ChatBox component
function ChatBox() {
// ...existing code...
const [editModalVisible, setEditModalVisible] = useState(false);
const [editingMessage, setEditingMessage] = useState<Message | null>(null);
const [editText, setEditText] = useState('');
const onUpdateMessage = useCallback(
(message: Message) => {
setEditingMessage(message);
setEditText(message.text);
setEditModalVisible(true);
},
[],
);
const handleUpdate = useCallback(async () => {
if (!editingMessage || !editText.trim()) {
console.log('Early return - missing data');
return;
}
updateMessage(editingMessage.serial, {text: editText.trim()}, {description: "Message update by user"})
.then((updatedMsg: Message) => {
console.log('Message updated:', updatedMsg);
setEditModalVisible(false);
setEditingMessage(null);
setEditText('');
})
.catch((error) => {
console.warn('Failed to update message', error);
// Still close the modal even if update fails
setEditModalVisible(false);
setEditingMessage(null);
setEditText('');
});
console.log('Update function completed');
}, [editingMessage, editText, updateMessage]);
const handleChange = (newValue: string) => {
setInputValue(newValue);
};
Update the rendering of messages in ChatBox
to enable the update action in the UI:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
return (
<View className="flex-1 flex-col">
<View className="flex-1 flex-row">
<View className="w-1/3 border-r border-blue-500">
{/* Add PresenceStatus component here */}
</View>
<ScrollView className="flex-1 p-4">
{messages.map((msg: Message) => {
const isMine = msg.clientId === 'my-first-client';
return (
<TouchableOpacity
key={msg.serial}
className={`flex ${isMine ? 'justify-end' : 'justify-start'} mb-2`}
onPress={() => onUpdateMessage(msg)}>
<View
className={`max-w-[60%] rounded-2xl px-3 py-2 shadow-sm ${
isMine
? 'bg-green-200 text-gray-800 rounded-br-none'
: 'bg-blue-50 text-gray-800 rounded-bl-none'
}`}>
<Text>{msg.text}</Text>
</View>
</TouchableOpacity>
);
})}
</ScrollView>
</View>
<View className="bg-white border-t border-gray-200">
{/* Row 1: Typing indicator */}
{/* Add typing indicator functionality here */}
{/* Row 2: Reactions */}
{/* Add Reactions component here */}
{/* Row 3: Text input & send button */}
<View className="flex flex-row items-center px-2 py-2">
<TextInput
className="flex-1 p-2 border border-gray-400 rounded outline-none bg-white"
placeholder="Type your message..."
value={inputValue}
onChangeText={handleChange}
onSubmitEditing={handleSend}
/>
<TouchableOpacity
className="bg-blue-500 text-white px-4 ml-2 h-10 flex items-center justify-center rounded"
onPress={handleSend}>
<Text className="text-white font-semibold">Send</Text>
</TouchableOpacity>
</View>
</View>
<Modal
animationType="slide"
transparent={true}
visible={editModalVisible}
onRequestClose={() => setEditModalVisible(false)}>
<View className="flex-1 justify-center items-center bg-black/50">
<View className="bg-white rounded-lg p-6 w-80">
<Text className="text-lg font-semibold mb-4">Edit Message</Text>
<TextInput
className="border border-gray-400 rounded p-2 mb-4"
value={editText}
onChangeText={setEditText}
placeholder="Enter new text..."
multiline
/>
<View className="flex-row justify-end">
<TouchableOpacity
className="px-4 py-2 mr-2"
onPress={() => setEditModalVisible(false)}>
<Text className="text-gray-600">Cancel</Text>
</TouchableOpacity>
<TouchableOpacity
className="bg-blue-500 px-4 py-2 rounded"
onPress={() => {
console.log('Update button pressed');
handleUpdate();
}}>
<Text className="text-white">Update</Text>
</TouchableOpacity>
</View>
</View>
</View>
</Modal>
</View>
);
Update the listener provided to the useMessages()
hook to handle the ChatMessageEventType.Updated
event:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// ChatApp.tsx - Replace the useMessages hook with the following:
const {sendMessage, updateMessage} = useMessages({
listener: (event: ChatMessageEvent) => {
const message = event.message;
switch (event.type) {
case ChatMessageEventType.Created: {
// Add the new message to the list
setMessages((prevMessages) => [...prevMessages, event.message]);
break;
}
case ChatMessageEventType.Updated: {
setMessages((prevMessages) => {
// Find the index of the message to update
const index = prevMessages.findIndex((other) => message.isSameAs(other));
// If the message is not found, return the previous messages
if (index === -1) {
return prevMessages;
}
// Apply the update to the original message
const newMessage = prevMessages[index].with(event);
// Create a new array with the updated message and return it
const updatedArray = prevMessages.slice();
updatedArray[index] = newMessage;
return updatedArray;
});
break;
}
default: {
console.error('Unhandled event', event);
}
}
}
});
Now, when you click on a previously sent message in the UI, it will prompt you to enter new text. After entering the required change and submitting, it will send the updated message to the room, where the listener will receive it and update the UI accordingly.
Step 6: Message history and continuity
Ably Chat enables you to retrieve previously sent messages in a room. This is useful for providing conversational context when a user first joins a room, or when they subsequently rejoin it later on. The useMessages()
hook exposes the historyBeforeSubscribe()
method to enable this functionality. This method returns a paginated response, which can be queried further to retrieve the next set of messages.
To do this, you need to expose historyBeforeSubscribe()
on the hook, and extend the ChatBox
component to include a method to retrieve the last 10 messages when the component mounts.
In your ChatApp.tsx
file, add the following useEffect
to your ChatBox
component:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// ChatApp.tsx - Add to ChatBox component
function ChatBox() {
// ...existing code...
const {sendMessage, updateMessage, historyBeforeSubscribe} = useMessages({
// ...existing code...
});
useEffect(() => {
async function loadHistory() {
try {
if (!historyBeforeSubscribe) return;
const history = await historyBeforeSubscribe({limit: 10});
setMessages(history.items);
} catch (error) {
console.error('Error loading message history:', error);
}
}
loadHistory();
}, [historyBeforeSubscribe]);
// ...existing code...
}
The above code will retrieve the last 10 messages when the component mounts, and set them in the state.
Try the following to test this feature:
- Use the Ably CLI to simulate sending some messages to the room from another client such as
ably rooms messages send --count 10 my-first-room 'Message number {{.Count}}'
- Refresh the app, this will cause the
ChatBox
component to mount again and call thehistoryBeforeSubscribe()
method. - You'll see the last 10 messages appear in the chat box.
Step 7: Show who is typing a message
Typing indicators enable you to display messages to clients when someone is currently typing. An event is emitted when someone starts typing, when they press a keystroke, and then another event is emitted after a configurable amount of time has passed without a key press.
The Chat SDK exposes the useTyping()
hook to enable this feature. The currentlyTyping
array from the hook tells you which clients are currently typing, allowing you to render them in the UI. The hook also exposes keystroke()
and stop()
methods to start and stop typing.
In your ChatApp.tsx
file, update the existing ChatBox
component. It should include the typing indicator hook, a function to handle text input and a modification to the existing handleSend
method so typing stops on message send:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// ChatApp.tsx - Update ChatBox component
function ChatBox() {
{/* ...existing code... */}
const {currentlyTyping, keystroke, stop} = useTyping();
const handleSend = () => {
{/* ...existing code... */}
stop().catch((err) => console.error('Error stopping typing', err));
};
const handleChange = (newValue: string) => {
setInputValue(newValue);
if (newValue.trim().length > 0) {
keystroke().catch((err) =>
console.error('Error starting typing', err),
);
} else {
stop().catch((err) => console.error('Error stopping typing', err));
}
};
}
To render the typing indicator, update the {/* Row 1: Typing indicator */}
part of ChatBox
rendering section like so:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
return (
<View className="flex-1 flex-col">
<View className="flex-1 flex-row">
{/* ...Existing code... */}
</View>
<View className="bg-white border-t border-gray-200">
{/* Row 1: Typing indicator */}
{/* Add typing indicator functionality here */}
{currentlyTyping.size > 0 && (
<View className="px-4 py-2 border-b border-gray-100">
<Text className="text-sm text-gray-700">
{Array.from(currentlyTyping).join(', ')}
{' '}
{currentlyTyping.size > 1 ? 'are' : 'is'} typing...
</Text>
</View>
)}
{/* ...Existing code... */}
</View>
);
When you start typing in the input box, your client will be indicated as typing, and if you clear all text, the indicator will stop. Other connected clients can also be displayed in the list if they're typing, you can use the Ably CLI to simulate typing from another client by running the following command:
ably rooms typing keystroke my-first-room --client-id "my-cli"
Step 8: Display who is present in the room
Display the online status of clients using the presence feature. This enables clients to be aware of one another if they are present in the same room. You can then show clients who else is online, provide a custom status update for each, and notify the room when someone enters it, or leaves it, such as by going offline.
The Chat SDK exposes both the usePresence()
and usePresenceListener()
hooks to interact with the presence feature. The usePresence()
hook allows you to enter the room and update your presence status, while the usePresenceListener()
hook allows you to subscribe to presence updates for the room.
The usePresenceListener()
hook also returns an object with the presenceData
array, which contains the current presence data for the room.
In your ChatApp.tsx
file, create a new component called PresenceStatus
like so:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// ChatApp.tsx
function PresenceStatus() {
usePresence();
const {presenceData} = usePresenceListener();
return (
<View className="flex flex-col bg-white w-full h-full px-4 py-2">
<Text className="text-green-700 font-semibold text-center border-b border-gray-900">
Online: {presenceData.length}
</Text>
<ScrollView className="flex-1 flex-col">
{presenceData.map((member, idx) => (
<View key={idx} className="flex flex-row items-center gap-1 my-2">
<View className="w-2 h-2 rounded-full bg-green-500" />
<Text className="text-gray-800">{member.clientId}</Text>
</View>
))}
</ScrollView>
</View>
);
}
Add the PresenceStatus
component to the ChatBox
component:
1
2
3
4
5
6
7
8
9
10
11
12
13
// Update ChatBox to include presence
function ChatBox() {
return (
<View className="flex-1 flex-col">
<View className="flex-1 flex-row">
<View className="w-1/3 border-r border-blue-500">
{/* Adding PresenceStatus component */}
<PresenceStatus />
</View>
<ScrollView className="flex-1 p-4">
{/* ...existing code... */}
);
}
You'll now see your current client ID in the list of present users.
You can also use the Ably CLI to enter the room from another client by running the following command:
ably rooms presence enter my-first-room --client-id "my-cli"
Step 9: Send a reaction
Clients can send a reaction to a room to show their sentiment for what is happening, such as a point being scored in a sports game.
Ably Chat provides a useReactions()
hook to send and receive reactions in a room. These are short-lived (ephemeral) and are not stored in the room history.
In your ChatApp.tsx
file, add a new component called ReactionComponent
, like so:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// ChatApp.tsx
function ReactionComponent() {
const reactions = ['👍', '❤️', '💥', '🚀', '👎', '💔'];
const [roomReactions, setRoomReactions] = useState<RoomReaction[]>([]);
const {sendRoomREaction} = useRoomReactions({
listener: (reactionEvent) => {
setRoomReactions((prev) => [...prev, reactionEvent.reaction]);
},
});
return (
<View>
{/* Reactions buttons */}
<View className="flex flex-row justify-evenly items-center px-4 py-2 border-t border-gray-300 bg-white">
{reactions.map((reaction) => (
<TouchableOpacity
key={reaction}
onPress={() =>
sendRoomREaction({name: reaction}).catch((err) =>
console.error('Error sending reaction', err),
)
}
className="text-xl p-1 border border-blue-500 rounded">
<Text className="text-blue-500">{reaction}</Text>
</TouchableOpacity>
))}
</View>
{/* Received reactions */}
<View className="flex flex-row gap-2 px-2 py-2 border-t border-gray-300">
<Text>Received reactions:</Text>
<ScrollView
horizontal
className="flex-1 flex-row"
showsHorizontalScrollIndicator={false}>
{roomReactions.map((r, idx) => (
<Text
key={idx}
className="px-2 py-1 bg-white rounded text-blue-600">
{r.name}
</Text>
))}
</ScrollView>
</View>
</View>
);
}
Add the ReactionComponent
component to the ChatBox
component:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Update ChatBox to include reactions
function ChatBox() {
return (
<View className="flex-1 flex-col">
<View className="flex-1 flex-row">
{/* ...Existing code... */}
</View>
<View className="bg-white border-t border-gray-200">
{/* ...Existing code... */}
{/* Row 2: Reactions */}
<ReactionComponent />
{/* ...Existing code... */
</View>
</View>
);
}
The above code should display a list of reactions that can be sent to the room. When you click on a reaction, it will send it to the room and display it in the UI.
You can also send a reaction to the room via the Ably CLI by running the following command:
ably rooms reactions send my-first-room 👍
Step 10: Disconnection and release
The disconnection and release section remains largely the same for React Native:
Automatic detachment on unmount
When a React Native component using the ChatRoomProvider
unmounts, the room will automatically detach and clean up all associated resources.
Closing the realtime connection
To close the realtime connection in React Native:
1
2
3
4
// In your ChatProviders.tsx or where you manage the realtime client
const handleDisconnect = () => {
realtimeClient.connection.close();
};
Next steps
Continue exploring Ably Chat with React Native:
Read more about the concepts covered in this guide:
- Read more about using rooms and sending messages.
- Find out more regarding presence.
- Understand how to use typing indicators.
- Send reactions to your rooms.
- Read into pulling messages from history and providing context to new joiners.
- Understand token authentication before going to production.
Explore the Ably CLI further, or check out the Chat JS API references for additional functionality.