build-a-modern-chat-application-with-react

In this tutorial, I will guide you to build your own group chat application using React, React Router, and CometChat Pro [https://www.cometchat.

Samuel Omole • Apr 21, 2020

In this tutorial, I will guide you to build your own group chat application using React, React Router, and CometChat Pro. Yes, rather than roll our own server, we will instead use CometChat Pro to handle the real-time sending and receiving of chat messages.

When you’re done, you should have a functional chat application that looks something like this (of course, you’re welcome to tweak and experiment with things as you go along):

I have structured this tutorial as a series of steps to make it easy to follow along. If you’d just like to check out the code, click here.

Setting up the project

Before we go too far, we must first setup our React project. To do this, we’ll use a lesser-known gem called Create React App.

The best thing? Because you have npm installed, you can use npx to install and run run create-react-app in one step:

After running this command, a new folder called “chatapp” will be created with the following structure:

In addition to React, we will also need to install React Router and CometChat Pro SDK. To do this, head to the chatapp directory and run:

Add React Router

In the end, our application will have two pages - one called Login where the user will login, and another called Groupchat where we will render the chat room. We will use React Router to route users to the page they need.

To setup React Router, we must first import the Router wrapper component in our index.js file. I call it a wrapper component because we wrap our App inside the Router component.

Replace index.js with this snippet:

index.js is the entry-point for our application. Its only real job is to render our React application. Most of our “real” logic happens in a file called App.js, which we will modify next.

In App.js, we must import additional React Router dependencies which will enable us to render different components depending on what route the user has loaded. For example, if the user goes to the “/login” route, we should render the Login component. Likewise, if the user goes to the “/chat” route, we should render the Groupchat component:

If you try to run this code it will definitely throw some errors because we haven’t made the Login and Groupchat components. Let’s do that now.

Create the Login component

To keep our project nice and tidy, create a folder called components to hold our custom components.

Then, in that newly-created folder, create a file called Login.js with the following code:

All we’re doing here is exporting a component with the heading text, “Login”. We’ll flesh this component out soon but for right now, we are merely creating boilerplate.

Create the Groupchat component

In the same components folder, create a new component called Groupchat.js:

As we progress through the tutorial, we will develop this humble component into the core of our chat application.

With the Groupchat and Login components in place, you should be able to run the application without an error. Open the app on localhost and navigate to localhost:3000/login and then localhost:3000/chat to see the components in action.

Create the CometChat APP ID and API key

Like I mentioned at the beginning of the tutorial, we won’t be rolling our own server in this tutorial. Instead, we’ll be using a hosted service of CometChat Pro.

Before we can connect to CometChat, we must first create a CometChat application from the dashboard:

Hold your horses ⚠️🐴!
To follow this tutorial or run the example source code you'll need to create a V1 application.

v2 will be out of beta soon at which point we will update this tutorial.

Once your application has been created, hit “Explore” then head to the “API Keys” tab:

Click “Create API key” and fill in the form, choosing Auth Only scope. From the table, you can note your application ID and application key, we’ll need these shortly.

Create the CometChat group ID

While we have the dashboard open, let’s also create a group. Normally you’d do this with code (for example, you might allow the user to create a custom chat group for their team or project through your app) but for learning and testing, the dashboard is fine.

Head to the “Groups” tab and create a new group called testgroup:

Like last time, you’ll be taken back to a table where you can note the group ID:

Take note as we’ll need this in the next step.

Create the configuration file

To make it easy to reference our configuration, create a new file called config.js and paste your credentials:

You can now close the dashboard. Once you setup CometChat, all interaction happens through code.

Create a CometChat Manager class

One of the beautiful things about React is that it lends itself to a separation of concerns. Our components can focus purely on presentation while we can create other modules to handle things like data fetching and state management.

To really take advantage of this, let’s create a new folder called “lib” and in that new folder, a file called chat.js. This is where all of our interaction with CometChat will take place:

Aside from allowing us to create a separation of concerns, presenting the code like this also makes it easier to digest.

Let me explain some important parts of this module, starting from the top:

  • LISTENER_KEY_MESSAGE - This is required by the message listener.

  • init() - This is required to be called only once throughout the lifecycle of the application, it calls the CometChat init method with the appID.

  • getTextMessage(uid, text, msgType) - it creates the message object based on CometChat.TextMessage method, it accepts the UID (GUID in our case) and the text message to send.

  • getLoggedInUser() - it’s used to get the currently logged in user.

  • login() - it’s used to log in a user based on the CometChat.login method, it takes in the UID (GUID in our case) and the apiKey.

  • getGroupMessages(GUID, callback, limit = 30) - this is used to get the previous group messages from CometChat using the CometChat.MessagesRequestBuilder() method that takes in the GUID and limit as parameters.

  • sendGroupMessage(UID, message)- this is used to send messages using the CometChat.sendMessage() method and it accepts the GUID and message as parameters.

  • joinGroup(GUID) - It’s used to join a chosen group using a GUID.

  • addMessageListener(callback) - Uses the CometChat.addMessageListener() to listen to messages (did I mention this is called in real-time?), it requires the LISTENER_KEY_MESSAGE as a parameter and also a callback that is called when a message is received.

There’s nothing specific to this application here. You could well take this module, expand it if needed, and import it into another project. Generally, though, this is just a thin wrapper around the SDK.

Update the login component

With all our configuration and chat code in place, we can now rapidly build out the UI starting with the Login component.

Just to remind you, this is what the Login component will look like:

As you can see, it’s main function is to ask the user for their name. Once a name is supplied, we render the Groupchat component.

Replace Login.js with:

Aside from the presentational HTML, most code here is dedicated to handling a React form.

Update the Groupchat component

The Groupchat component has a lot more responsibility than the Login component. As a quick reminder, this is what it will look like:

For the most part, the Groupchat component’s job is to bridge the chat lib module and the UI we’ll present to the user. For example, when a user sends a message, we call chat.sendMessage and as new messages trickle in, a callback function is called:

There’s a lot to digest here, so let’s break the important parts down:

  • sendMessage() - This function handles sending a message to the group, passing the GUID and the text message that is stored is in the component’s state. If the user is not part of the group we then make a request to join the group and then call the sendMessage function again.

  • scrollToBottom() - This function will be used as a callback function for the message listener, it just makes sure that the latest messages are shown in the chat list.

  • handleSubmit() - This calls the sendMessage function.

  • getUser() - This calls the chat.getLoggedInUser() method and stores the user object in the component’s state.

  • messageListener() - This calls the chat.addMessageListener() function and appends every new message received to the groupMessage array which is stored in the component’s state and rendered in the app.

  • componentDidMount() - This calls the getUser and messageListener functions.

Finally, we render a class depending on if the message is ours or someone else's. This way, we can apply different styles which is the topic of the next section.

Update the styles

If you were to run the application now, it would work but with no CSS to speak of thus far, it would look quite uh, odd.

This isn’t a tutorial about CSS so I won't explain it in any detail, but to help you follow along, you can paste the following into your App.css file(you will have one already because it was generated by create-react-app earlier):

Conclusion

Run the application with npm start and low and behold, your chat application is complete. At least, the basic functionality is in place. With CometChat, you could easily expand the app to include a “who’s online list”, direct messages, media messages, and a bunch of other features.

Samuel Omole

CometChat

Samuel, React developer from Nigeria 🇳🇬. Follow me on Twitter @AjeboDeveloper

Share it with everyone!

Try out CometChat in action

Experience CometChat's messaging with this interactive demo built with CometChat's UI kits and SDKs.