```shell
npm create vite@latest my-chat-react-app -- --template react-ts
```
2. Setup Tailwind CSS for styling the application. Ensure you import tailwind in your local `App.CSS` file and add it to your `vite.config.ts` file. For installation instructions, see the [Tailwind CSS documentation for Vite](https://tailwindcss.com/docs/guides/vite).
```shell
npm install tailwindcss @tailwindcss/vite
```
3. Install the Ably Chat SDK, this will also install the Ably Pub/Sub SDK as a dependency:
```shell
npm install @ably/chat ably
```
4. Create a `.env` file in your project root and add your API key:
```shell
echo "VITE_ABLY_API_KEY=your-api-key" > .env
```
### (Optional) Install Ably CLI
Use the [Ably CLI](https://github.com/ably/cli) as an additional client to quickly test chat features. It can simulate other users by sending messages, entering presence, and acting as another user typing a message.
1. Install the Ably CLI:
```shell
npm install -g @ably/cli
```
2. Run the following to log in to your Ably account and set the default app and API key:
```shell
ably login
```
```react
// App.tsx
import React, {useCallback, useEffect, useState} from 'react';
import "./App.css";
import {
ChatRoomProvider,
useChatConnection,
useMessages,
usePresence,
usePresenceListener, useRoom, useRoomReactions,
useTyping
} from '@ably/chat/react';
import {
ChatMessageEvent,
Message,
ChatMessageEventType,
RoomReaction
} from '@ably/chat';
```
## 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 components. The [`AblyProvider`](https://ably.com/docs/getting-started/react-hooks.md#ably-provider) and [`ChatClientProvider`](https://sdk.ably.com/builds/ably/ably-chat-js/main/typedoc/functions/chat-react.ChatClientProvider.html) should be used at the top level of your application, typically in `main.tsx`. These are required when working with the [`useChatConnection`](https://sdk.ably.com/builds/ably/ably-chat-js/main/typedoc/functions/chat-react.useChatConnection.html) hook and [`ChatRoomProvider`](https://sdk.ably.com/builds/ably/ably-chat-js/main/typedoc/functions/chat-react.ChatRoomProvider.html) exposed by Ably Chat.
In production, you should use [token authentication](https://ably.com/docs/auth/token.md) to avoid exposing your API keys publicly, the [`clientId`](https://ably.com/docs/auth/identified-clients.md) is used to identify the client.
Replace the contents of your `src/main.tsx` file with the following code to set up the providers:
```react
// main.tsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import * as Ably from 'ably';
import { ChatClient, LogLevel } from '@ably/chat';
import { ChatClientProvider } from '@ably/chat/react';
import { AblyProvider } from 'ably/react';
import App from './App'; // Your main app component
// Create your Ably Realtime client and ChatClient instances:
const realtimeClient = new Ably.Realtime({
key: import.meta.env.VITE_ABLY_API_KEY,
clientId: 'my-first-client',
});
const chatClient = new ChatClient(realtimeClient, {
logLevel: LogLevel.Info,
});
ReactDOM.createRoot(document.getElementById('root')!).render(
{/* Your main app component */}
,
);
```
## 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`.
In your project, open `src/App.tsx`, and add the following functions along with the imports from the previous step:
```react
// App.tsx
// This component will display the current connection status
function ConnectionStatus() {
// Hook to get the current connection status
const { currentStatus } = useChatConnection();
return (
Ably Chat Connection
Connection: {currentStatus}!
);
}
function App() {
return (
);
}
export default App;
```
Run your application by starting the development server:
```shell
npm run dev
```
Open your browser to [localhost:5173](http://localhost:5173), and you will see the connection status reflected in the UI: `"Currently 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`](https://sdk.ably.com/builds/ably/ably-chat-js/main/typedoc/functions/chat-react.ChatRoomProvider.html)
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()`](https://sdk.ably.com/builds/ably/ably-chat-js/main/typedoc/functions/chat-react.useRoom.html) hook,
which you can be used to interact with the room and monitor its status.
In your project, open `src/App.tsx`, and add a new component called `RoomStatus`:
```react
// App.tsx
function RoomStatus() {
// This component will display the current room status
const [currentRoomStatus, setCurrentRoomStatus] = useState('');
const {roomName} = useRoom({
onStatusChange: (status) => {
setCurrentRoomStatus(status.current); // Update the room status
},
});
return (
Room Status
Status: {currentRoomStatus}
Room: {roomName}
);
}
```
Update your main app component to include the `ChatRoomProvider` and nest the `RoomStatus` component inside it:
```react
// App.tsx
function App() {
// Wrap your Room component with the ChatRoomProvider:
return (
{/* Your RoomStatus component should go here */}
);
}
export default App;
```
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()`](https://sdk.ably.com/builds/ably/ably-chat-js/main/typedoc/functions/chat-react.useMessages.html) hook to interact with the [messages](https://ably.com/docs/chat/rooms/messages.md) feature of the Chat SDK. After the room provider is set up, you can use the [`useMessages()`](https://sdk.ably.com/builds/ably/ably-chat-js/main/typedoc/functions/chat-react.useMessages.html) hook to send and receive messages in the room.
In your project, open `src/App.tsx`, and add a new component called `ChatBox`, like so:
```react
// App.tsx
function ChatBox() {
const [inputValue, setInputValue] = useState('');
// State to hold the messages
const [messages, setMessages] = useState([]);
// The useMessages hook subscribes to messages in the room and provides a send method
const { sendMessage } = useMessages({
listener: (event: ChatMessageEvent) => {
const message = event.message;
switch (event.type) {
case ChatMessageEventType.Created: {
setMessages((prevMessages) => {
// Check if the incoming message is correctly ordered
if (prevMessages.length > 0 && prevMessages[prevMessages.length - 1].serial > message.serial) {
// If the message arrived out of order - you should find the correct insertion point based on serial
// This is omitted for brevity, but production code should maintain serial order
}
return [...prevMessages, message];
});
break;
}
default: {
console.error('Unhandled event', event);
}
}
}
});
// Function to handle sending messages
const handleSend = () => {
if (!inputValue.trim()) return;
sendMessage({ text: inputValue.trim() }).catch((err) =>
console.error('Error sending message', err))
setInputValue('');
};
return (
{messages.map((msg: Message) => {
const isMine = msg.clientId === 'my-first-client';
return (
{msg.text}
);
})}
setInputValue(e.target.value)}
onKeyDown={(event) => {
if (event.key === 'Enter') {
handleSend();
}
}}
/>
);
}
```
Add the `ChatBox` component to your main app component:
```react
// App.tsx
function App() {
return (
{/* Your ChatBox component should go here */}
);
}
```
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:
```shell
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()`](https://sdk.ably.com/builds/ably/ably-chat-js/main/typedoc/interfaces/chat-js.Messages.html#updatemessage) method of the Chat SDK [messages](https://ably.com/docs/chat/rooms/messages.md) 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:
```react
// App.tsx - Place this in the ChatBox component
const onUpdateMessage = useCallback(
(message: Message) => {
const newText = prompt('Enter new text');
if (!newText) {
return;
}
updateMessage(
message.serial,
{
text: newText,
metadata: message.metadata,
headers: message.headers,
},
).catch((error: unknown) => {
console.warn('Failed to update message', error);
});
},
[updateMessage],
);
```
Update the rendering of messages in the chat box to enable the update action in the UI:
```react
// App.tsx - Update the rendering of messages in the ChatBox component
return (
{messages.map((msg: Message, idx: number) => {
const isMine = msg.clientId === 'my-first-client';
return (
onUpdateMessage(msg)}
>
{msg.text}
);
})}
setInputValue(e.target.value)}
onKeyDown={(event) => {
if (event.key === 'Enter') {
handleSend();
}
}}
/>
);
```
Update the listener provided to the `useMessages()` hook to handle the `ChatMessageEventType.Updated` event:
```react
// App.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) => other.serial === message.serial);
// If the message is not found, return the previous messages
if (index === -1) {
return prevMessages;
}
// The updated message is already in event.message, so we use that directly
const updatedArray = prevMessages.slice();
updatedArray[index] = message;
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()`](https://sdk.ably.com/builds/ably/ably-chat-js/main/typedoc/interfaces/chat-js.Messages.html#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 `src/App.tsx` file, add the following `useEffect` to your `ChatBox` component:
```react
// App.tsx
function ChatBox() {
/* Expose historyBeforeSubscribe() */
/* const {sendMessage, updateMessage, historyBeforeSubscribe} = useMessages({...*/
/* existing code */
useEffect(() => {
async function loadHistory() {
try {
if (!historyBeforeSubscribe) {
// The room is not ready yet
return;
}
// Retrieve the last 10 messages
const history = await historyBeforeSubscribe({ limit: 10 });
// Set the messages in the state
setMessages(history.items);
} catch (error) {
console.error('Error loading message history:', error);
}
}
loadHistory();
}, [historyBeforeSubscribe]);
/* rest of your 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:
1. Use the ably CLI to simulate sending some messages to the room from another client.
2. Refresh the page, this will cause the `ChatBox` component to mount again and call the `historyBeforeSubscribe()` method.
3. 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()`](https://sdk.ably.com/builds/ably/ably-chat-js/main/typedoc/functions/chat-react.useTyping.html) 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 `src/App.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:
```react
// App.tsx
function ChatBox() {
/* existing code */
// Expose the currentlyTyping set and the keystroke and stop methods
const { currentlyTyping, keystroke, stop } = useTyping();
/* replace the existing handleSend method with the following */
const handleSend = () => {
if (!inputValue.trim()) return;
sendMessage({text: inputValue.trim()}).catch((err) =>
console.error('Error sending message', err))
setInputValue('');
/* stop typing when the message is sent */
stop().catch((err) => console.error('Error stopping typing', err))
};
/* add the following method to handle input changes */
const handleChange = (e: React.ChangeEvent) => {
const newValue = e.target.value;
setInputValue(newValue);
if (newValue.trim().length > 0) {
// If the input value is not empty, start typing
keystroke().catch(
(err) => console.error('Error starting typing', err))
} else {
// If the input is cleared, stop typing
stop().catch(
(err) => console.error('Error stopping typing', err))
}
};
/* rest of your code */
```
To render the typing indicator, update `ChatBox` rendering section like so:
```react
// App.tsx - ChatBox component
return (
{messages.map((msg: Message, idx: number) => {
const isMine = msg.clientId === 'my-first-client';
return (
onUpdateMessage(msg)}
>
{/* message update handling */}
{msg.text}
);
})}
{/* Typing indicator */}
{currentlyTyping.size > 0 && (
{Array.from(currentlyTyping).join(', ')}
{' '}
{currentlyTyping.size > 1 ? 'are' : 'is'} typing...
)}
{/* Text input & message sending */}
{
if (event.key === 'Enter') {
handleSend();
}
}}
/>
);
```
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:
```shell
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()`](https://sdk.ably.com/builds/ably/ably-chat-js/main/typedoc/functions/chat-react.usePresence.html) and [`usePresenceListener()`](https://sdk.ably.com/builds/ably/ably-chat-js/main/typedoc/functions/chat-react.usePresenceListener.html) 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()`](https://sdk.ably.com/builds/ably/ably-chat-js/main/typedoc/functions/chat-react.usePresenceListener.html) hook also returns an object with the `presenceData` array, which contains the current presence data for the room.
In your `src/App.tsx` file, create a new component called `PresenceStatus` like so:
```react
// App.tsx
function PresenceStatus() {
// The usePresence hook enters the current client into the room presence
usePresence();
// The usePresenceListener hook subscribes to presence updates for the room
const { presenceData } = usePresenceListener();
return (
Online: {presenceData.length}
{presenceData.map((member, idx) => (
{member.clientId}
))}
);
}
```
Add the `PresenceStatus` component to your main app component like so:
```react
// App.tsx
function App() {
return (
{/* Your PresenceStatus component should go here */}
);
}
```
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:
```shell
ably rooms presence enter my-first-room --client-id "my-cli"
```
## Step 9: Send a room 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 [`useRoomReactions()`](https://sdk.ably.com/builds/ably/ably-chat-js/main/typedoc/functions/chat-react.useRoomReactions.html) hook to send and receive reactions in a room. These are short-lived (ephemeral) and are not stored in the room history.
In your `src/App.tsx` file, add a new component called `ReactionComponent`, like so:
```react
// App.tsx
function ReactionComponent() {
const reactions = ['👍', '❤️', '💥', '🚀', '👎', '💔'];
const [roomReactions, setRoomReactions] = useState([]);
const { sendRoomReaction } = useRoomReactions({
listener: (reactionEvent) => {
setRoomReactions([...roomReactions, reactionEvent.reaction]);
},
});
return (
{/* Reactions buttons */}
{reactions.map((reaction) => (
))}
{/* Received reactions */}
Received reactions:
{roomReactions.map((r, idx) => (
{r.name}
))}
);
}
```
Add the `ReactionComponent` component to your main app component:
```react
// App.tsx
function App() {
// Wrap your Room component with the ChatRoomProvider:
return (
{/* Your ReactionComponent component should go here */}
);
}
```
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:
```shell
ably rooms reactions send my-first-room 👍
```
## Step 10: Disconnection and release
When you're done with a room or your application is unmounting, it's important to properly clean up resources to prevent memory leaks and unnecessary network usage.
### Automatic detachment on unmount
For React components, when a component using the `ChatRoomProvider` unmounts, the room will automatically detach from the underlying channel and clean up associated resources. This behavior is controlled by the `release` prop on the `ChatRoomProvider`:
```react
// App.tsx
{/* Your components */}
```
### Closing the realtime connection
It's important to note that no unmount process exists for disconnecting the Ably realtime connection. If you need to do this, you can call `realtimeClient.connection.close()` directly:
```react
import * as Ably from 'ably';
const realtimeClient = new Ably.Realtime({
key: import.meta.env.VITE_ABLY_API_KEY,
clientId: 'my-first-client',
});
const handleDisconnect = () => {
realtimeClient.connection.close();
};
// Call handleDisconnect when needed
```
This will close the connection to Ably and clean up any associated resources.
## Next steps
Continue to explore the documentation with React as the selected language:
* Understand [token authentication](https://ably.com/docs/auth/token.md) before going to production.
* Read more about using [rooms](https://ably.com/docs/chat/rooms.md) and sending [messages](https://ably.com/docs/chat/rooms/messages.md).
* Find out more regarding [presence](https://ably.com/docs/chat/rooms/presence.md).
* Read into pulling messages from [history](https://ably.com/docs/chat/rooms/history.md) and providing context to new joiners.
Explore the [Ably CLI](https://www.npmjs.com/package/@ably/cli) further, or check out the [Chat JS API references](https://sdk.ably.com/builds/ably/ably-chat-js/main/typedoc/modules/chat-js.html) for additional functionality.