Build a React chat app with image sharing

Chat applications have evolved and are now a major part of modern communication tools. Its applications range from communications, team engagements, products reports and feedbacks as well as technical support systems.

Peter Eze • Apr 21, 2020

Chat applications have evolved and are now a major part of modern communication tools. Its applications range from communications, team engagements, products reports and feedbacks as well as technical support systems. It has become a major part of our daily lives, hence, the need to make it even more robust for users. Often while we chat, we feel the need to send more than just texts, maybe share images, documents or even contacts. In this post, we’ll show you how to build a CometChat application that does just that. With this app, we take your chat app development experience up a notch by building to send/receive not just texts but files too.

Audience and learning goal

This tutorial is best suited for developers who are looking to incorporate chat features and functionalities into an existing product or to build one from scratch. In the end, you will learn how to build a React chat application with text and file-sharing capabilities. You will also learn how to create and use CometChat API’s to build out working chat applications.

Before we proceed, here’s a visual representation of the functioning application we'll build.

Next, we will walk through the processes of building this app from scratch. However, you can jump straight to the code repository on Github if you wish to.

Prerequisites

To follow along with this tutorial, you will need:

  • Basic knowledge of React.js - a JavaScript front-end development framework for building intuitive user interfaces.

  • Familiarity with API’s and chat features will be an added advantage but not mandatory to follow along.

  • You also need to have Node and NPM installed on your development machine. If you don't have it, install it here.

  • Fair knowledge of React Hooks is necessary to clearly understand the snippets shared in this post. If you're new to React Hooks feel free to read this post first.

  • Finally, you will need to have a free account with CometChat, feel free to create one here.

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.

Getting started

First, create a React project and set up CometChat configurations. To do this, open your terminal or command prompt and run the command below:

Install CometChat and Bootstrap
Next, let’s install CometChat into our app for easy chat build. Simply run this command:

If you’ve successfully installed all the dependencies, the dependencies section of your package.json file should look like this:

The next thing we need to do is to configure CometChat to communicate with our React app. To do this, you will need to use the CometChat credentials in your CometChat dashboard. If you created an account at the beginning as instructed, navigate to your account dashboard and copy your API_KEY (Remember to keep it safe) and your APP_ID.

Next, create a config.js file within the src folder where we can define our application configurations:

Create the application components

Before we go any further, let's take a minute to understand the structure of our app. Basically, we'll have just two components — Login and Chat. When the app loads, we render the Login component so users can supply their credentials and log into the app. When the login process is successful, we render the chat component. With that said, let's go ahead and create these components.

Take the following steps:

  • In the src folder, create a new components folder

  • Navigate into the components folder and create the Login.js and Chat.js files

We'll update these files with the appropriate code contents as we progress through the post, in the meantime, let's initialize CometChat and render the components when the app loads.

Initialize CometChat

When the app loads, we need to initialize CometChat inside the entry file. This is important because we need to login users into our chat app and we can't do that unless CometChat is initialized. Open the App.js file in the project root directory and update it with the code below:

‍Here, we initialized CometChat with the appID we defined the config.js file earlier. We are also conditionally rendering the components — If a user exists (someone has logged in) render the Chat component. But if that is not the case, render the Login component.

Login component

Now that we have that functionality, let's go ahead and set up the Login component to handle the actual logging in of our users. Open the Login.js file and update it with the code below:

Here, we defined a userID variable to hold the username from the form when a user fills it. Then we use the supplied username and API key to log in the user. Once logged in, we update the User prop with the currently logged in user. This will then notify the App.js file to render the Chat component. Everything else going on here is just basic React form handling concepts.

Chat component

The Chat component comprises of other functionalities that we'll briefly talk about now. First when the component loads, we display a list of friends that the logged-in user can chat with. When a particular friend is selected from the list, we remove the list from the DOM and bring up the chatbox where the actual conversation will happen.

Fetch friends
First, let's implement the Friendslist function that will fetch and render all available friends for the logged-in user to select from. While performing the fetch request to get available friends, it's important to keep the user engaged with a Spinner or Progress Dialog. Let's install the React MD Spinner to help us handle that. Open your terminal and run the command:

That done, we can go ahead and implement the fetch request within the Chat.js file like so:

‍Here, we've passed down three variables from props:
friends — Holds a list of the fetched friends.
friendisLoading — Holds the loading state of the request.
selectedFriend — Holds the selected friend from the rendered list.

While the fetch request is in progress, the friendisLoading variable will be true and the Spinner will be visible, when the request is completed and friends are loaded, we render a list of the fetched friends.

Like we mentioned earlier, when the user selects a friend to chat with (from the list of friends) we want to remove the list from the DOM since we won't be needing it anymore.

Chat functionality
First, we'll perform the actual request to fetch the friends and update the values of the variables we've defined. This is also where we pass the updated values to props.

‍Next, when the user selects a friend from the list, we want to fetch previous messages if any. We also want to add text and media message listeners to listen for incoming messages and update the Chat state accordingly. When new messages come in, we also want to scroll the view to the current message.

Here, when the user selects a friend, we update the boxMessage variable with the name of the selected friend. Then we make a request to fetch the previous messages between the two users if any. We've also attached a message listener to monitor incoming text and media messages to update the chat UI accordingly.
So far, we have used two functions that we haven't defined yet — selectFriend() and scrollToBottom(). We didn't forget, we are just getting to it and this is the time define them:

Next, let's create the Chatbox component. This component will be responsible for fetching the previous message history between users and also render incoming text and media messages to the view

‍Just like in the Friendlist component, we also rendered the Spinner when the component is performing the request to fetch previous messages.

Next, let's define the return() function for our Chat component to render the actual chat interface where users can type, pick/send files and messages:

Here, we are using Bootstrap classes to layout our chat UI. We rendered the Friendlist component first to present the user with a list of friends to select from. Then we rendered the Chatbox component to display the messages between the users. Finally, we created the form that holds the UI elements (Text Input, File Input, and Send File Button) that controls the chat functionality.

I'm sure you noticed that we used Font Awesome icons and you're probably wondering when we added that, well we haven't. 😃 Let's do that now. Back to your terminal, run the following command:

From the previous code snippet above, we passed in the handleSubmit() function to execute when the form is submitted. We also did the same with the Send File button. When the button is clicked, we call the sendFile() function. At the moment, we haven't defined either of those so let's do that now — TODO 5:

Custom styles
Finally, the focus of this tutorial is building a functional chat app, hence I won’t explain the CSS in great detail so we don't deviate so much from the app. To apply the custom styling we've defined for the app open your App.css file and update it with the styles below:

Alternatively, can also open the source code and copy the codes into your project.

Test the chat functionality
At this point, you can run the app. Open a new terminal window in the project's root directory and run the command below to start the development server:

Now when you navigate to your browser on localhost:3000 you should see the app running and the chat app functioning as expected.

Conclusion

This brings us to the end of this journey. Gradually we've been able to build a full chat application with realtime delivery and file sharing functionalities. This is only a part of all the things you can do with CometChat, you can take this tutorial further to add more features that are available on CometChat —  Online presence indication, chat notifications, group chat functionalities, and more.

Peter Eze

CometChat

-

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.