Getting started: Chat with React
This guide will get you started with Ably Chat on a new React application built with Vite.
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 + TypeScript project using Vite. For detailed instructions, refer to the Vite documentation.
npm create vite@latest my-chat-react-app -- --template react-ts
- Setup Tailwind CSS for styling the application. Ensure you import tailwind in your local
App.CSS
file and add it to yourvite.config.ts
file. For installation instructions, see the Tailwind CSS documentation for Vite.
npm install tailwindcss @tailwindcss/vite
- Install the Ably Chat SDK, this will also install the Ably Pub/Sub SDK as a dependency:
npm install @ably/chat
Adding required imports
You will need the following imports in your src/App.tsx
file, these will be used at various points in the guide:
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
and ChatClientProvider
should be used at the top level of your application, typically in main.tsx
. These are required when working with the useChatConnection
hook and ChatRoomProvider
exposed by Ably Chat.
Replace the contents of your src/main.tsx
file with the following code to set up the providers:
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:
Run your application by starting the development server:
npm run dev
Open your browser to 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
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 src/App.tsx
, and add a new component called RoomStatus
:
Update your main app component to include the ChatRoomProvider
and nest the RoomStatus
component inside it:
The above code creates a room with the ID my-first-room
and sets up a listener to monitor the room status. It also displays the room ID 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 your project, open src/App.tsx
, and add a new component called ChatBox
, like so:
Add the ChatBox
component to your main app component:
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 update()
method of the Chat SDK messages feature.
Expose the update()
method from the useMessages()
hook and then add a method to the ChatBox
component to handle the edit action like so:
Update the rendering of messages in the chat box to enable the update action in the UI:
Update the listener provided to the useMessages()
hook to handle the MessageEvents.Updated
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 getPreviousMessages()
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 getPreviousMessages()
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:
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.
- Refresh the page, this will cause the
ChatBox
component to mount again and call thegetPreviousMessages()
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 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:
To render the typing indicator, update ChatBox
rendering section like so:
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 src/App.tsx
file, create a new component called PresenceStatus
like so:
Add the PresenceStatus
component to your main app component like so:
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 src/App.tsx
file, add a new component called ReactionComponent
, like so:
Add the ReactionComponent
component to your main app component:
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
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
:
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:
This will close the connection to Ably and clean up any associated resources.
Next steps
Continue exploring Ably Chat with React:
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.