React
This guide will help you quickly add TalkJS to your React app. 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, creating a chatbox and starting a conversation.
To make the most of this guide, you will need:
- A TalkJS account
- A basic understanding of React
- A React app that you will add TalkJS to
To get started, install @talkjs/react
along with the regular talkjs
package:
1npm install talkjs @talkjs/react
To synchronize data between a browser tab and TalkJS, you need to create a new connection to the TalkJS servers, known as a session.
Our React SDK provides a built-in Session component. The connection to the TalkJS servers will live as long as the Session
component is mounted.
Import the Session
component in the component where you want to add your chat session:
1import { Session } from '@talkjs/react';
If you want to listen for events or show desktop notifications for new messages, we recommend putting the session at the top of your component hierarchy, so that it is active even when no chat UI is being shown.
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 we can use.
In TalkJS, a user is a person that uses your app. The Session
component requires a current user to send messages as. To test it out, we'll use the userId
prop to specify the user ID of an existing user, the sample_user_alice
sample user that comes with Test Mode by default:
1import { Session } from '@talkjs/react';23function ChatComponent() {4 return <Session appId="<APP_ID>" userId="sample_user_alice"></Session>;5}67export default ChatComponent;
So far, we have created a connection to the TalkJS server and added our sample user. Next, we want to create the chat UI and have a conversation.
TalkJS offers multiple pre-built chat UIs out of the box for your project. This guide uses the chatbox, but the other UIs work the same way.
Import the Chatbox
component in the component where you want to have your chat UI (this should be a descendant of your Session
component so it has access to the connection):
1import { Chatbox } from '@talkjs/react';
Next, add the Chatbox
component. The component requires you to specify the current conversation. We'll use the conversationId
prop to select an built-in sample conversation with an ID of sample_conversation
. We'll also pass in a style
prop with some CSS styling to set the size of the chatbox:
1<Chatbox2 conversationId="sample_conversation"3 style={{ width: '100%', height: '500px' }}4></Chatbox>
Check your browser, and you should see a fully-featured chat window running in your app that looks something like this:
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.
So far in this guide we've used a sample user and conversation. Next, we'll create and sync a new user. 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';34function ChatComponent() {5 const syncUser = useCallback(6 () =>7 new Talk.User({8 id: 'nina',9 name: 'Nina',11 photoUrl: 'https://talkjs.com/new-web/avatar-7.jpg',12 welcomeMessage: 'Hi!',13 role: 'default',14 }),15 []16 );1718 return (19 <Session appId="<APP_ID>" syncUser={syncUser}>20 // Chatbox component goes here...21 </Session>22 );23}2425export default ChatComponent;
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 Chatbox
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 welcome
and add one other user:
1const syncConversation = useCallback((session) => {2 // JavaScript SDK code here3 const conversation = session.getOrCreateConversation('welcome');45 const other = new Talk.User({6 id: 'frank',7 name: 'Frank',9 photoUrl: 'https://talkjs.com/new-web/avatar-8.jpg',10 welcomeMessage: 'Hey, how can I help?',11 role: 'default',12 });13 conversation.setParticipant(session.me);14 conversation.setParticipant(other);1516 return conversation;17}, []);1819// ...2021<Chatbox22 syncConversation={syncConversation}23 style={{ width: '100%', height: '500px' }}24></Chatbox>;
You should see something like this:
In this short 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 group chat by adding more users, create a new UI theme, or enable email notifications. For more ideas, try browsing the many examples we offer for different use cases.
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';45function ChatComponent() {6 const syncUser = useCallback(7 () =>8 new Talk.User({9 id: 'nina',10 name: 'Nina',12 photoUrl: 'https://talkjs.com/new-web/avatar-7.jpg',13 welcomeMessage: 'Hi!',14 role: 'default',15 }),16 []17 );1819 const syncConversation = useCallback((session) => {20 // JavaScript SDK code here21 const conversation = session.getOrCreateConversation('welcome');2223 const other = new Talk.User({24 id: 'frank',25 name: 'Frank',27 photoUrl: 'https://talkjs.com/new-web/avatar-8.jpg',28 welcomeMessage: 'Hey, how can I help?',29 role: 'default',30 });31 conversation.setParticipant(session.me);32 conversation.setParticipant(other);3334 return conversation;35 }, []);3637 return (38 <Session appId="<APP_ID>" syncUser={syncUser}>39 <Chatbox40 syncConversation={syncConversation}41 style={{ width: '100%', height: '500px' }}42 ></Chatbox>43 </Session>44 );45}4647export default ChatComponent;