Build a Slack clone using React and CometChat

In this tutorial, you will learn how to build a group chat app similar to Slack with React and CometChat [https://www.cometchat.

In this tutorial, you will learn how to build a group chat app similar to Slack with React and CometChat.

Here’s a preview of what you’ll build:

As you can see, users can “login” then create, join, and communicate in channels.

Coming into this article, you probably have at least some experience with React but what is CometChat?

Good question, I am glad you asked!

CometChat is a service which enables you to build chat features into your application without the need to worry about back-end code. This way, you can focus on the features unique to your application (in this case, team communication).

You’ll learn more about CometChat as you follow along so without any further adieu, let’s get started.

Create a CometChat Pro App

First things first, you’ll need to create a CometChat app.

Head to the dashboard (create a free account if you haven’t already), and you’ll see this page:

Enter your app name, I called mine “Group Chat”, then click the + button to create your app.

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 created, click Explore to view the app:

From the left sidebar, click API Keys then Create API Key:

Call your key what you like, I named mine “Group Chat” after the app, but make sure to select Auth Only from the Scope dropdown.

Take note of your API Key and App id because you’ll need them later in your code:

API keys are a core concept in CometChat, which you can read more about here.

With your app in place, let’s move on to the client and setup React.

Setting up React

Nowadays, there are many ways to scaffold a React application. To scaffold ours, we’ll use a popular tool called create-react-app:

Once the command has finished running, install react-router-dom too:

{% c-line %} npm install react-router-dom --save{% c-line-end %}

Your directory structure should look like this:

Create a configuration file

With our CometChat app and React boilerplate in place, we should create a configuration file to hold the APP_ID and API_KEY that we just created.

Create a file in the src directory called settings.js and paste the following:

Remember to replace "{API_ID}" and "{API_KEY}" with your own values from the dashboard.

Next, let’s install and initialise CometChat.

To install CometChat, run the following command:

{% c-line %} npm install @CometChat-pro/chat --save{% c-line-end %}

Once installed, head to App.js where we will initialise CometChat from the constructor:

It’s useful to initialise CometChat in a container component (in our case, App) so we can make it accessible throughout our React application.

Run the app from the command-line with npm start.

If the connection to CometChat is successful (in other words, if you copied your credentials correctly), you should see a success message like: “Initialization completed successfully true” in your console.

If you don’t see this message something is wrong. The most common cause for problems is that your credentials are incorrect so make sure to double-check.

Create Your App Components

Our chat application is going to have a Login component, a Dashboard container component, a Channel component and ChatBox component:

The truth is, most of the time will need container components that take responsible for providing and managing data and behavior to their child components.

In our case, the Channel and ChatBox components are children of and managed by the Dashbaord container component. The differences between container and children components is nuanced, you can read more about the difference here

I like to organize my components into directories. So, for each component we’ll create a directory. The content of each directory will be an index.js, index.css.

In the end, your application structure will look a little like this:

But perhaps we are getting ahead of ourselves… Before delving too far into the code, let me give you an overview of how the application will work.

A user will log into the application with their username (from the Login component).

To keep things simple, we won’t allow the user to sign up. Instead, they can pick a username from the demo users provided by CometChat namely, “superhero1”, “superhero2”, “superhero3”, "superhero4”, and - you guessed it “superhero5”.

You can create additional users from the dashboard (handy for testing and while developing) or using the create use API.

After a user logs in, they will be redirected to what we will call the Dashboard component. Dashboard is a container component that renders and manages the Chatbox and the Channel components. Users can click on any channel to start chatting in that channel.

Login Component

Naturally, the first component we should create is the login component to identify users:

Create a new folder called component/Login to hold files related to the Login component.

Then create a file called component/Login/index.js:

In the same directory, create another file called index.css and paste the contents of lindex.css.

“Paste this code” isn’t exactly educational but regrettably, styling is a bit outside the scope of this tutorial. Our focus is on React and CometChat so while I will share a link to the file, I won’t explain it in this tutorial.

You’ll also want to download loading.svg and save it in the same directory. When the user logs in, we’ll show them this loading spinner to let them know things are working in the background.

So, what is happening here?

At the top of index.js, we import our API_KEY as well as react-router-dom, which will enable us to redirect the user to the chat if their login is successful.

The most important code happens in a function called login where we authenticate the user:

If login returns a user (in other words, if the login was successful), we’ll update our redirect state to true which indicates to the render function that we should redirect the user to the Dashboard:

If something went wrong, we show an error to the user and hide the spinner:

Dashboard container component

Create a new folder called component/Dashboard to hold files related to the Dashboad component.

Then create a file called component/Dashboard/index.js:

In the same directory, create index.css and paste the contents of this index.css file.

Our Dashboard component is a container component, which means it’s job is to fetch and manage data for it’s children components, in this case: Channels and ChatBox:

The Channels component, outlined in red is to show the user channels to pick from.

The ChatBox component, outlined in green is where chat messages are input and rendered:

The Dashboard coordinates these components so, for example, if someone clicks on a channel, Dashboard knows abut it and updates ChatBox accordingly.

See this function:

It’s responsible for updating the state of the dashboard with the channeluid from the Channle’s component.

In the updateState function, we are also updating the isShowMessages property. We set it to true to indicate that a group has been selected and the ChatBox should render the messages for the selected group.

With all of that said, we haven’t actually yet defined the Channels or ChatBox components. Let’s do that next.

Channels Component

Create a new folder called component/Channels to hold files related to the Login component.

Then create a file called component/Channels/index.js:

In the same directory, create another file called index.css and paste the contents of this file.

In index.js, We fetch the list of channels easily using this function:

Here, we create an instance of the GroupRequestBuilder which, in turn, returns a list of groups or, as we call them in our app, channels. Even though CometChat uses the term groups, we use channels - just like Slack channels.

ChatBox Component

Create a new folder called component/ChatBox to hold files related to the Chatbox component.

Then create a file called component/ChatBox/index.js:

And, like I am sure you expect by now, create another file in the same directory called index.css and paste the code from this file.

That is a lot of code to digest, let me break it down.

At the top of index.js, and as per usual, we import React, CometChat and our component styles:

Then, in the constructor we set the receiverID based on a prop provided by the Dashboard container component:

In this case, the receiverID denotes the group ID to send and receive messages to and from.

The dashbaord can update this any time, for example, if a new channel is selected.

In componentDidUpdate, we fetch historical messages using the MessagesRequestBuilder:

Likewise, when the component mounts, we begin to listen for new messages in real-time:

To send new messages, we simply use the sendMessage function:

Create Channel Component

We can provide our users with some default channels, but we also want to empower them to create their own.

To enable this, create a new folder called component/CreateGroup to hold files related to the CreateGroup component.

Then create a file called component/CreateGroup/index.js:

In the same directory, create another file called index.css and paste the contents of GroupChat/index.css from GitHub.

This component boils down to making a cal to createGroup:

Generally, the main function of our components is to bridge the cap between the UI and CometChat. We don’t need to write custom logic for basic chat functionality because CometChat handles it all behind the scene.

Conclusion

There you have it. Your group chat app with react and CometChat Pro.

If you made it this far, you are the real MVP.

The entire code for this tutorial can be found here.

There is so much you can do with CometChat Pro, register to get your API credentials and let me know what you built with it.

If you need a hand, let us know — we are always ready to help.

Try out CometChat in action

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