DEV Community

Aswin Rajeev for TalkJS

Posted on

How to build a chat into a React app with TalkJS

In today’s tutorial, we will add a group chat for students to an existing React application using the TalkJS Chat API. As a pre-requisite, you will need to sign up with TalkJS and get your APP_ID from the Dashboard which will be used to identify your account. For the sake of this article, we have created a fictitious application with React that will be used by students from a specific university to view live lectures. The live lectures will be supplemented with a group chat feature that lets the students ask questions to the lecturer. The source code for the entire project can be downloaded from GitHub.

App Home Screen

Application Overview

This fictitious application is run by John Doe University on their intranet to provide live lectures to its students. Since it is on their intranet, students are already expected to be authenticated with the university. Once they land on the main page, they are expected to enter their student ID, name, and email address, which will then take them to the live lecture. For the sake of simplicity, the lecture we have used is a video from YouTube and all students will be redirected to the same lecture. The article will focus more on the integration of the group chat to an existing React application.

Adding TalkJS to a React application

To add TalkJS to your existing React application, use the following command:
npm install talkjs –-save
If you are using the yarn package manager, you should use the command yarn add talkjs.
To use it in the component of your choice, import TalkJS using the following statement.
import Talk from "talkjs";

Component Walkthrough

The application has two main components. One is the Home component and the other is the VideoLecture component. The Home component contains the form that takes the information from the student and then routes them to the VideoLecture component. The handleSubmit() method is of interest here as it handles storage of the student details as well as the redirection.

handleSubmit(event) {
  localStorage.setItem("id", this.state.id);
  localStorage.setItem("name", this.state.name);
  localStorage.setItem("email", this.state.email);
  history.push("/viewLiveLecture");
  event.preventDefault();
}
Enter fullscreen mode Exit fullscreen mode

React’s thin history library is used here to perform the redirection. All the details for the routes are mentioned in the Routes component. The details entered by the user are stored in the local storage for ease of access across all components.

export default class Routes extends Component {
    render() {
        return (
            <Router history={history}>
                <Switch>
                    <Route path="/" exact component={Home} />
                    <Route path="/home" exact component={Home} />
                    <Route path="/viewLiveLecture" component={VideoLecture} />
                </Switch>
            </Router>
        )
    }
}
Enter fullscreen mode Exit fullscreen mode

The majority of the logic for TalkJS is housed inside the VideoLecture component. The entire code is present inside the constructor. We will take a look at it section by section.

Retrieving student details

this.id = localStorage.getItem("id");
this.userName = localStorage.getItem("name");
this.emailId = localStorage.getItem("email");
Enter fullscreen mode Exit fullscreen mode

We create three variables to hold the user id, user name, and email address. This is accessed from the local storage.

Creating the Users and the TalkJS Session

   Talk.ready
      .then(() => {
        const me = new Talk.User({
          id: this.id,
          name: this.userName,
          email: this.emailId,
          photoUrl: `https://randomuser.me/api/portraits/men/${this.id}.jpg`,
          role: "default",
        });
        const other = new Talk.User({
          id: "1",
          name: "Prof. George Larry",
          email: "george@larry.net",
          photoUrl: "https://randomuser.me/api/portraits/men/83.jpg",
          role: "default",
        });
        if (!window.talkSession) {
          window.talkSession = new Talk.Session({
            appId: "YOUR_APP_ID_HERE",
            me: me,
          });
        }
Enter fullscreen mode Exit fullscreen mode

We use the then() function on the Talk object which can be chained multiple times and returns a Promise. The first thing to do is to set the users in the conversation. Note that the other user here is always the professor who is hosting the lecture and the current user will be the student who enters the live lecture room.
To identify the student, we set their id, username, and email address from what they enter on the Home page. This is also used to retrieve their profile picture. The last step here is to create a session using the APP_ID, from the TalkJS dashboard, and the current user.

Creating the Conversation object

  const conversation = window.talkSession.getOrCreateConversation("999");
  conversation.setAttributes({
    subject: "Robotics: 101"
  });
  conversation.setParticipant(me);
  conversation.setParticipant(other);
  this.chatbox = window.talkSession.createChatbox();
  this.chatbox.select(conversation);
  this.chatbox.mount(this.container);
  })
  .catch((e) => console.error(e));
Enter fullscreen mode Exit fullscreen mode

Once the session and users are created, we will create the conversation object. We are assigning a static id for the conversation here so that all students log in to the same room. In a real use case, the conversation id can be the lecture’s unique key which will then be mapped to all the students taking that module.
To make the subject appear at the top, we have set the attribute ‘subject’ on the conversation object. Again, in a real scenario, this can be retrieved from the database or service. We then set the participants of the conversation and create a chatbox. This is then mounted inside the component shown below.

<div
  className="talk-js-chatbox flex-child"
  ref={(c) => (this.container = c)}
></div>
Enter fullscreen mode Exit fullscreen mode

We have themed the chat a little so that it stays consistent with the university website and looks more like a group chat in a live lecture. Since this article is more about adding group student chat into an existing React application, we will not discuss about theming here. You can check out these articles for reference.

TalkJS UI Customization Tutorials

Here are some additional tutorials on how you can customize the TalkJS UI using our powerful Theme Editor.

Wrapping up

Live Lecture with Student Group Chat

With that, we have successfully added TalkJS to our existing React application. With very minimal code changes, we were able to add a fully working group chat to our fictitious university’s live lecture. Group Chats in TalkJS supports up to 20 users in the Basic plan and up to 40 users in the Growth plan. If your use case requires more than 40 users, you can also go for the Enterprise plan. You can access the complete source code on GitHub, read more about Group Chats, and also about the versatile Theme Editor on TalkJS.

Top comments (4)

Collapse
 
aswinrajeevofficial profile image
Aswin Rajeev

Hi,

Thank you for your feedback. Will look into that going forward. Just wanted to keep this tutorial as simple as possible.

Also, yes, functional components and hooks can also be used in place of Class components. More on that here:

talkjs.com/docs/Getting_Started/Fr...

Collapse
 
alibahaari profile image
Ali Bahaari

I've not read your post and a simple question: Does it work with web socket?

Collapse
 
_bigblind profile image
Frederik 👨‍💻➡️🌐 Creemers

Hi Ali,

TalkJS uses websockets behind the scenes, but the websocket endpoint is not meant to be used directly.

Collapse
 
alibahaari profile image
Ali Bahaari

Thanks for the response.