How to build a LinkedIn-like Messaging App with React and TalkJS - Part 2
Tags: react, javascript, messaging, tutorial
Published: 2019-12-23 12:31:58

---
title: How to build a LinkedIn-like Messaging App with React and TalkJS - Part 2
published: true
description: This tutorial will show you how you can easily integrate a chat feature into an app using TalkJS. It will serve as a step-by-step guide to integrate TalkJS into any React application. 
tags: #react #javascript #messaging #tutorial

---

In the [first part of the tutorial](https://dev.to/talkjs/how-to-build-a-linkedin-like-messaging-app-with-react-and-talkjs-part-1-n9c), we saw how we can build a LinkedIn-like messaging app without chat. In this part, we will see how we can easily integrate chat into this app or any other React application. In case you missed it,  here's [a live demo of the app](https://talkjs.com/demos/react/linkedin-messaging-app) we are trying to build. Let's continue by setting up TalkJS in our app.

<h3 id="talkjs-section"> Setting up TalkJS</h3>

#### Creating an account and adding user roles

First, you will have to create an account with TalkJS. To do this, visit [the TalkJS website](http://talkjs.com/). On the navigation menu, you will a blue button that says “Try for Free”. Click on this button and create an account. If this is successful, you will be redirected to your TalkJS dashboard. Take note of your `APP ID` which you will be using later in this tutorial. 

TalkJS allows different groups of users to have different settings by assigning them a ['role'](https://talkjs.com/docs/Reference/Concepts/Roles.html). You have full control over which user gets which role. Since we want features like file sharing and location sharing in our app, we need to create a role on our TalKJS dashboard. 

To create a role, scroll down the page to where you see roles. Click on the “+” button to create a new role. We will call our role `Member`. Click on the Save button. Next,  settings for this user will be displayed. Click on enable file sharing and location sharing and any other setting you want to enable. 


![Talkjs Dashboard](https://paper-attachments.dropbox.com/s_E7612E1A04D31375D81EE173B96C13C086977BA1E8A29BE4374DBC2130C73390_1567122112961_Screen+Shot+2019-08-30+at+12.41.17+AM.png)


#### Adding TalkJS to the App

Setting up TalkJS on your React app is quite easy too. To install, we run the following command.
```
npm install talkjs --save
```
When this is done, you can use TalkJS in any file in our project by importing it.
```
import Talk from "talkjs";
```
That is it for setting up TalkJS. Now let us move to build the application.

### Setting up the Chatbox

First, we import TalkJS into the file
```js
    import React, { Component } from 'react';
    import Talk from "talkjs";
    import { dummyUsers } from "./Users";
    
    ...
```
Next, we add a method that handles the click of the “message” button event. Add this to the component.

```js
    ...    
    handleClick(userId) {
    
            /* Retrieve the two users that will participate in the conversation */
            const { currentUser } = this.state;
            const user = dummyUsers.find(user => user.id === userId)
    
            /* Session initialization code */
            Talk.ready
            .then(() => {
                /* Create the two users that will participate in the conversation */
                const me = new Talk.User(currentUser);
                const other = new Talk.User(user)
    
                /* Create a talk session if this does not exist. Remember to replace the appId with the one on your dashboard */
                if (!window.talkSession) {
                    window.talkSession = new Talk.Session({
                        appId: YOUR_APP_ID,
                        me: me
                    });
                } 
                
                /* Get a conversation ID or create one */
                const conversationId = Talk.oneOnOneId(me, other);
                const conversation = window.talkSession.getOrCreateConversation(conversationId);
                
                /* Set participants of the conversations */
                conversation.setParticipant(me);
                conversation.setParticipant(other);
    
                /* Create and mount chatbox in container */
                this.chatbox = window.talkSession.createChatbox(conversation);
                this.chatbox.mount(this.container);
            })            
            .catch(e => console.error(e));
        }
```
There is a lot going on in the code above. Let us analyse what is going in it.

Users need to belong to a Talk session to use TalkJS. A user does not need to log directly into TalkJS to do this. Rather, in our app, we ensure that only users logged in on our app can have a TalkJS session. We do this session initialisation in lines `9-21`. You can find your APP ID on your TalkJS dashboard. Remember to replace `YOUR_APP_ID` with it.

Lines `24-30` creates a conversation between the two users, then creates and mount the chatbox.

For this method to be useful, we have to call it when any of the “message” buttons are clicked. We also need to pass the `userId` of the user as we call the `handleClick` method. Let us do that. Replace the button in the render method with the following code.

```js
     ...
         <div className="user-action">
             <button onClick={(userId) => this.handleClick(user.id)}>Message</button>
          </div>
    
    ...
```
We also need to add the container which the chatbox will be mounted on. So in the render method, we also add the following. 
```js
...
     </ul>
         <div className="chatbox-container" ref={c => this.container = c}>
             <div id="talkjs-container" style={{height: "300px"}}><i></i>        </div>
             </div>
         </div>
    ...
```
Go ahead and click on any of  the “message” buttons now. You should see the chatbox pop up when you click on any of them.

To make it look more LinkedIn-like, let us position the chatbox to the bottom right of the page by styling the `chatbox-container` class. So add the following style to your `App.css` file.

```css
.chatbox-container {
  position: absolute;
  bottom: 0;
  height: 400px;
  right: 5%;
  width: 300px;
}
```
This should be the page when you click on any of the message buttons.


![The completed MyNetwork page](https://paper-attachments.dropbox.com/s_E7612E1A04D31375D81EE173B96C13C086977BA1E8A29BE4374DBC2130C73390_1567120968595_Screen+Shot+2019-08-30+at+12.21.36+AM.png)


That is it. We have made significant progress. Did you notice how easy it is to set up a chat feature? Go ahead and start a conversation with any of the dummy users. Of course, they cannot reply to you because they are dummy users.

Let us move on to our last component - the messaging component.


### Creating the Messaging Component

The messaging component holds a list of all conversations the current user has had with other users just like on LinkedIn. TalkJS also makes it easy to set this up. Let’s create a basic component.

```js
import React, { Component, Fragment } from 'react';
import Talk from "talkjs";
    
class Messaging extends Component {
    
    render() {
        return (
            <Fragment>
                <div style={{height: '500px'}} className="inbox-container" ref={c => this.container = c}>Loading...</div>
            </Fragment>
        );
    }
}
      
export default Messaging;
```
Remember to import this file in the `App.js` file and create a route for it.
```js
...
import Login from './Components/Login';
import MyNetwork from './Components/MyNetwork';
import Messaging from './Components/Messaging';
    
...
    
...
    
            <Route path="/" exact component={Login}/> 
            <Route path="/mynetwork" component={MyNetwork}/>
            <Route path="/messaging" component={Messaging}/>
         </Router>
     </div>
...
```
You should see just the loading… message on the screen right now.

Let us set up the TalkJS Inbox. First, we retrieve the current user from the local storage and add it to the state of the component. TalkJS will use this to fetch the conversations and add it to the state. In line 4,  we initialise the value of inbox.

```js
constructor(props) {
    super(props);
    
    this.inbox = undefined;
    let currentUser;
    const currentTalkjsUser = localStorage.getItem('currentTalkjsUser');
    if (currentTalkjsUser) {
        currentUser = JSON.parse(currentTalkjsUser)
    }
    
    this.state = {
        currentUser
    }
}
```
 
Next, we add a  `componentDidMount` lifecycle method and set up the inbox there.
```js
componentDidMount() {
    Talk.ready
        .then(() => {
            const me = new Talk.User(this.state.currentUser);
                    
            if (!window.talkSession) {
                window.talkSession = new Talk.Session({
                    appId: YOUR_APP_ID,
                    me: me
                 });
            }
                
            this.inbox = window.talkSession.createInbox();
            this.inbox.mount(this.container);
      
        })
        .catch(e => console.error(e));
}

```   
Notice that this is quite similar to how we created the chatbox. There are subtle differences though. 

In lines `13-14`, instead of using `createChatbox`, we used `createInbox`. Also, we did not have to create another user, since this basically displays the previous conversations you have had with users.

If you have added the above code, you should see the inbox now. If you started any conversation using the chatbox, you should see it in the inbox. Otherwise, it displays “You have not started any conversation”.


![Messaging page with conversation](https://paper-attachments.dropbox.com/s_E7612E1A04D31375D81EE173B96C13C086977BA1E8A29BE4374DBC2130C73390_1567121531332_Screen+Shot+2019-08-30+at+12.31.28+AM.png)


Congrats for making it this far. You have built yourself a LinkedIn-like messaging app.


### Conclusion

In this tutorial, we have seen how easy it is to use TalkJS to add a messaging feature to your React app. TalkJS removes all the complex work of using APIs and building a user interface for your messages.

We built a login page to retrieve the current user’s data. We also built a “MyNetwork” page which is similar to the LinkedIn “MyNetwork”. On this page, we displayed a list of users and a button which enables the user to send messages to any user on the list. We used TalkJS to setup the chatbox. Lastly, we built the Messaging component using TalkJS Inbox.

I hope you had fun building this because I did. You can check [the Github repo for the full code.](https://github.com/talkjs/talkjs-examples/tree/master/react/linkedin-like-app)

For further reading, you can refer to the following documents.
[Getting Started with TalkJS](https://talkjs.com/docs/Getting_Started/index.html)
[The TalkJS inbox](https://talkjs.com/docs/Features/Chat_UI_Modes/The_Inbox.html)
[The TalkJS Chatbox](https://talkjs.com/docs/Features/Chat_UI_Modes/The_Chatbox.html)