Prerequisites
Ably
- Sign up for an Ably account.
- Create a new app, and get your first API key. You can use the root API key that is provided by default, within the API Keys tab to get started.
Create a New Project
- Create a new React + TypeScript project using Vite. For detailed instructions, refer to the Vite documentation.
- Setup Tailwind CSS for styling the application. Ensure you import tailwind in your local
App.CSSfile and add it to yourvite.config.tsfile. For installation instructions, see the Tailwind CSS documentation for Vite.
- Install the Ably Chat SDK, this will also install the Ably Pub/Sub SDK as a dependency:
- Create a
.envfile in your project root and add your API key:
Step 1: Set 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. TheAblyProvider and ChatClientProvider should be used at the top level of your application, typically in main.tsx.
In production, you should use token authentication to avoid exposing your API keys publicly, the clientId is used to identify the client.
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 aChatClientProvider.
In your project, open src/App.tsx, and add the following functions:
Run your application by starting the development server:
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. TheChatRoomProvider provides access to a specific chat room to all child components in the component tree.
Update your main app component to include the ChatRoomProvider:
Step 4: Send a Message
Messages are how your clients interact with one another and Ably Chat exposes auseMessages() hook to interact with the messages feature of the Chat SDK.
Add a new component called ChatBox to send and receive messages:
Add the ChatBox component to your main app component:
Next Steps
Continue to explore the documentation with React as the selected language:- Understand token authentication before going to production
- Read more about using rooms and sending messages
- Find out more regarding presence
- Read into pulling messages from history and providing context to new joiners
