1-on-1 chat

This guide will help you quickly add TalkJS to your React app and create a 1-on-1 chat between two users. It uses TalkJS's React SDK, which provides pre-built chat UI components for your application. We'll use it alongside the JavaScript SDK, which we'll use for data manipulation tasks like synchronizing users and conversations.

In the guide we'll walk you through installing TalkJS, viewing an existing conversation, and creating new users and conversations.

Prerequisites

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

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

Install TalkJS

To get started, install @talkjs/react along with the regular talkjs package:

1npm install talkjs @talkjs/react

Connect to TalkJS

To use TalkJS in your app, you'll need to create a connection to the TalkJS servers, known as a session.

Our React SDK provides a built-in Session component. Import the Session component in the component where you want to add your chat session:

1import { Session } from '@talkjs/react';

We recommend rendering the session component at the top of your component hierarchy. The connection to the TalkJS servers will live as long as the Session component is mounted, so that it is active even when no chat UI is being shown. This allows you to continue to listen for events or show desktop notifications for new messages.

Next, add the Session component:

1import { Session } from '@talkjs/react';
2
3function Chat() {
4 return <Session appId="<APP_ID>" userId="sample_user_alice"></Session>;
5}
6
7export default Chat;

You'll need to provide the Session component with your TalkJS App ID through the appId prop. You can find your App ID in the Settings tab of the TalkJS dashboard. For this tutorial, we recommend using the App ID for TalkJS's Test Mode, which has built-in sample users and conversations that you can use.

You'll also need to specify a current user to send messages as. In this example, we've used the userId prop to specify the user ID of an existing user, the sample_user_alice sample user.

View an existing conversation

So far, we have created a connection to the TalkJS servers and added our sample user. Next, we want to create the chat UI and view an existing conversation.

TalkJS offers multiple pre-built chat UIs out of the box for your project, including a chatbox, inbox, and popup UI.

Import your preferred UI component in the component where you want to have your chat (this should be a descendant of your Session component, so it has access to the connection):

1import { Chatbox } from '@talkjs/react';

Next, add your UI component:

1<Chatbox
2 conversationId="sample_conversation"
3 style={{ width: '100%', height: '500px' }}
4></Chatbox>

You'll need to specify the conversation that you want to view. We'll use the conversationId prop to view a built-in sample conversation with an ID of sample_conversation. For the chatbox and inbox UI, we'll also pass in a style prop with some CSS styling to set the size of the chat.

Check your browser, and you should see a fully-featured chat window running in your app. For example, for the chatbox that'll look something like this:

Loading chat...

Try sending Sebastian a message! You can also try switching your userId to sample_user_sebastian and viewing the other side of the conversation.

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

Create new users and conversations

So far in this guide we've used a sample user and conversation. Next, we'll create new users and a conversation between them, and sync them with the TalkJS servers.

Let's start with the current user in our session. Usually, you would create users based on the data from your database. For this getting started guide, we've hard-coded our user data instead.

We'll use the JavaScript SDK to create the user. To do this, we'll first replace the userId prop in the Session component with the syncUser prop. The syncUser prop takes a callback that creates a Talk.User object:

1import Talk from 'talkjs';
2import { useCallback } from 'react';
3
4function Chat() {
5 const syncUser = useCallback(
6 () =>
7 new Talk.User({
8 id: 'nina',
9 name: 'Nina',
10 email: '[email protected]',
11 photoUrl: 'https://talkjs.com/new-web/avatar-7.jpg',
12 welcomeMessage: 'Hi!',
13 }),
14 []
15 );
16
17 return (
18 <Session appId="<APP_ID>" syncUser={syncUser}>
19 // UI component will go here...
20 </Session>
21 );
22}
23
24export default Chat;

If you sync a User object with the same ID later, any properties that have changed will be updated. Otherwise, if nothing has changed the user stays the same.

If you prefer, you can instead create and sync users from your backend with our REST API. If you want to only sync users with the REST API, you can disable syncing in the browser and only pass in user IDs with the userId prop that we used earlier in this guide. See Browser Synchronization for more details.

Next, we'll sync a new conversation by replacing the conversationId prop in the UI component with the syncConversation prop. This prop takes a callback that uses the JavaScript SDK to create a conversation with getOrCreateConversation. If the conversation ID already exists, TalkJS will load the pre-existing conversation and all previous messages. Otherwise, it creates a new conversation.

As with users, you can instead choose to sync conversations from your backend with our REST API, and only pass in conversation IDs with the conversationId prop.

In our case, we'll create a conversation with an ID of new_conversation and add one other user:

1const syncConversation = useCallback((session) => {
2 // JavaScript SDK code here
3 const conversation = session.getOrCreateConversation('new_conversation');
4
5 const other = new Talk.User({
6 id: 'frank',
7 name: 'Frank',
8 email: '[email protected]',
9 photoUrl: 'https://talkjs.com/new-web/avatar-8.jpg',
10 welcomeMessage: 'Hey, how can I help?',
11 });
12 conversation.setParticipant(session.me);
13 conversation.setParticipant(other);
14
15 return conversation;
16}, []);
17
18// ...
19
20<Chatbox
21 syncConversation={syncConversation}
22 style={{ width: '100%', height: '500px' }}
23></Chatbox>;

You should see something like this:

Example chat with synced user and conversation

Next steps

In this guide, you've added powerful user-to-user chat to your React app. 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. For example, you could create a new UI theme in the Theme Editor, customize your chat with action buttons or HTML panels, or enable email notifications.

For more ideas, try browsing the many examples we offer for different use cases.

Before you go live, make sure you enable authentication. Authentication keeps your user data secure, by ensuring that only legitimate users can connect to your chat. For details, see: Authentication.

Full code example

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

1import { useCallback } from 'react';
2import Talk from 'talkjs';
3import { Session, Chatbox } from '@talkjs/react';
4
5function Chat() {
6 const syncUser = useCallback(
7 () =>
8 new Talk.User({
9 id: 'nina',
10 name: 'Nina',
11 email: '[email protected]',
12 photoUrl: 'https://talkjs.com/new-web/avatar-7.jpg',
13 welcomeMessage: 'Hi!',
14 }),
15 []
16 );
17
18 const syncConversation = useCallback((session) => {
19 // JavaScript SDK code here
20 const conversation = session.getOrCreateConversation('new_conversation');
21
22 const other = new Talk.User({
23 id: 'frank',
24 name: 'Frank',
25 email: '[email protected]',
26 photoUrl: 'https://talkjs.com/new-web/avatar-8.jpg',
27 welcomeMessage: 'Hey, how can I help?',
28 });
29 conversation.setParticipant(session.me);
30 conversation.setParticipant(other);
31
32 return conversation;
33 }, []);
34
35 return (
36 <Session appId="<APP_ID>" syncUser={syncUser}>
37 <Chatbox
38 syncConversation={syncConversation}
39 style={{ width: '100%', height: '500px' }}
40 ></Chatbox>
41 </Session>
42 );
43}
44
45export default Chat;