React

Even if you're well-experienced with React, it can be confusing to integrate a new SDK. The easiest way to learn is by trying the features for yourself. But for that, you need a working project that you can play around with.

This quick-start guide will help you add TalkJS in your React app for the first time. We cover the core concepts of TalkJS, and introduce you to its JavaScript SDK.

Prerequisites

To make the most of this tutorial, you will need:

  1. A TalkJS account
  2. A basic understanding of React
  3. A React app that you will add TalkJS to

Installing TalkJS

To get started, you will need to install TalkJS in your React app:

npm install talkjs --save

Then, import TalkJS into the component you want to use for chat:

JavaScript
import Talk from 'talkjs';

TalkJS is loaded asynchronously to improve the performance of your site. Before we can use it, we need to make sure that TalkJS is fully loaded and ready to use. To do that, we wait for the Talk.ready promise to resolve before making any calls to the TalkJS SDK.

import { useEffect, useState } from 'react';
function MyChatComponent() {
// wait for TalkJS to load
const [talkLoaded, markTalkLoaded] = useState(false);
Talk.ready.then(() => markTalkLoaded(true));
useEffect(() => {
if (talkLoaded) {
// Safe to use the SDK here
}
}, [talkLoaded]);
}

Talk.ready is a regular JavaScript promise, so you can .then or await it at any point.

Creating users

In TalkJS, a 'User' is a person that uses your app. Typically, you will have one TalkJS user for each user in your own database. Each connection to TalkJS has to specify a 'Current User' to send messages as.

Usually, you would create users based on the data from your database. For this simple example, we'll hard-code one instead:

JavaScript
// After `Talk.ready`
const currentUser = new Talk.User({
id: '1',
name: 'Henry Mill',
photoUrl: 'henry.jpeg',
welcomeMessage: 'Hello!',
role: 'default',
});

Remember, anything using the Talk API should sit inside useEffect or componentDidMount, after waiting for Talk.ready.

There's not much point in a chat app with only one person using it, so let's create another user:

JavaScript
// After `Talk.ready`
const otherUser = new Talk.User({
id: '2',
name: 'Jessica Wells',
photoUrl: 'jessica.jpeg',
welcomeMessage: 'Hello!',
role: 'default',
});

Connecting to TalkJS

To synchronize data between a browser tab and TalkJS, you need to create a new connection, known as a session. The session will stay open until the user navigates away from the page, and it automatically synchronizes data in both directions with the TalkJS servers.

To create a new session, you will need your 'App ID' and a user to send messages as (the 'Current User'). You can find YOUR_APP_ID in the TalkJS dashboard.

useEffect(() => {
if (talkLoaded) {
// Create users here
const session = new Talk.Session({
appId: 'YOUR_APP_ID',
me: currentUser,
});
return () => session.destroy();
}
}, [talkLoaded]);

Starting a conversation

So far, we have loaded TalkJS, created some users, and opened a connection to the server. Now we need to let them talk to each other.

A 'Conversation' is a place for two or more users to chat. That could mean a simple direct message between users, or it might be something fancier. TalkJS works with all kinds of conversations, from group chats to product-specific haggling.

We will use that last example, and create a conversation between 'Henry' and 'Jessica':

JavaScript
// After `Talk.ready` and creating users
const conversationId = Talk.oneOnOneId(currentUser, otherUser);
const conversation = session.getOrCreateConversation(conversationId);
conversation.setParticipant(currentUser);
conversation.setParticipant(otherUser);

If these users have talked before, the auto-generated conversationId is the same, meaning TalkJS will load the pre-existing conversation and all previous messages. Otherwise, it creates a new conversation.

Adding the UI

At this point, everything is set up to allow our users to chat. All we need is a user interface.

TalkJS offers multiple UIs out of the box for your project. This guide uses the chatbox, but the other UIs work the same way.

Create a new chatbox and select the conversation we made earlier. This tells the UI which conversation it should display.

JavaScript
// After creating the conversation
const chatbox = session.createChatbox();
chatbox.select(conversation);

To display our chatbox on the page, we need to mount it on the DOM. This requires a reference to the element we want to mount it on. We create a div element and store a reference with useRef:

import { useEffect, useState, useRef } from 'react';
function MyChatComponent() {
const chatboxEl = useRef();
/* useState, useEffect, etc */
return <div ref={chatboxEl} />;
}

Now we can pass that reference to chatbox.mount, which displays the chatbox UI inside our div:

// After chatbox.select
chatbox.mount(chatboxEl.current);

Check your browser, and you should see a fully-featured chat window running in your app. Try sending Jessica a message, and have a play around with TalkJS!

If you don't see the chat window, make sure that you entered your App ID, replacing YOUR_APP_ID in the code.

Next Steps

In this short guide, you've taken your React app to the next level with powerful user-to-user chat. You also learned more about the fundamentals of TalkJS, and how it all fits together. Most importantly, you've built a starting point to try out all the features TalkJS offers.

You could create a group chat by adding more users, create a new UI theme, or even enable email notifications! If you're hungry for more, try browsing the many examples we offer for different use cases.

Full code example

Here's what your working example should look like, in full.

import Talk from 'talkjs';
import { useEffect, useState, useRef } from 'react';
function MyChatComponent() {
const chatboxEl = useRef();
// wait for TalkJS to load
const [talkLoaded, markTalkLoaded] = useState(false);
useEffect(() => {
Talk.ready.then(() => markTalkLoaded(true));
if (talkLoaded) {
const currentUser = new Talk.User({
id: '1',
name: 'Henry Mill',
photoUrl: 'henry.jpeg',
welcomeMessage: 'Hello!',
role: 'default',
});
const otherUser = new Talk.User({
id: '2',
name: 'Jessica Wells',
photoUrl: 'jessica.jpeg',
welcomeMessage: 'Hello!',
role: 'default',
});
const session = new Talk.Session({
appId: 'YOUR_APP_ID',
me: currentUser,
});
const conversationId = Talk.oneOnOneId(currentUser, otherUser);
const conversation = session.getOrCreateConversation(conversationId);
conversation.setParticipant(currentUser);
conversation.setParticipant(otherUser);
const chatbox = session.createChatbox();
chatbox.select(conversation);
chatbox.mount(chatboxEl.current);
return () => session.destroy();
}
}, [talkLoaded]);
return <div ref={chatboxEl} />;
}