How to Build a React Chat App

Written by mundiazm | Published 2022/12/29
Tech Story Tags: chat | react | reactjs | mobile-app-development | app | app-development | software-development | react-tutorial

TLDRThis tutorial uses the MinChat react chat sdk to build a react chat app. We are going to use a UI Kit called Chat UI Kit React for the chat UI. By the end of this tutorial, you will have a fully functioning react chat application.via the TL;DR App

Welcome to this tutorial on building a react chat app using the MinChat Chat SDK! In this article, we will be creating a fully functional react chat application, entirely on the front-end, using React.js. You won't need any server-side code – we will let the MinChat SDK handle all of the back-end work for us. By the end of this tutorial, you will have a fully functioning react chat application that you can customize and use however you like. Let's get started!'

You can find the source code for this tutorial on Github.

The lead image of this article was generated via HackerNoon's AI Stable Diffusion model using the prompt 'chatbot app'.

Step 1: Breaking the react chat UI into components

This tutorial uses the MinChat react chat sdk.

To begin building a react chat app, it is important to understand that React is centered around the concept of components. The first step in creating a react chat app is to break down the chat UI into individual react chat components. One key component to start with is the root component, which serves as the common ancestor for all other components in the app. This root component will be the "App" component.

function App() {
  return (
    <div style={{ position: "relative", height: "500px" }}>
      {/* ui components */}
    </div>
  );
}

We are going to use a UI Kit called Chat UI Kit React for the chat UI. go ahead and run the following command in the terminal

npm install @chatscope/chat-ui-kit-react @chatscope/chat-ui-kit-styles

Now lets add the react chat ui components to our App.js file

import styles from "@chatscope/chat-ui-kit-styles/dist/default/styles.min.css";
import {
  MainContainer,
  ChatContainer,
  MessageList,
  Message,
  MessageInput,
} from "@chatscope/chat-ui-kit-react";

function App() {
  return (
    <div style={{ position: "relative", height: "500px", width: "500px" }}>
      <MainContainer>
        <ChatContainer>
          <MessageList>
            <Message
              model={{
                message: "Hello World",
                sender: "Joe",
              }}
            />
          </MessageList>
          <MessageInput placeholder="Type message here" />
        </ChatContainer>
      </MainContainer>
    </div>
  );
}

export default App;

Your chat UI looks like this:

Step 2: Configuring MinChat

We are going to signup for an account on MinChat and get an API Key.

Install the MinChat React chat sdk:

npm install @minchat/react

Lets create our two users who will be sending messages between each other:

const firstUser = {
  id: "micheal",
  name: "Micheal Saunders",
};

const secondUser = {
  id: "mercy",
  name: "Mercy Wells",
};

Lets wrap the root index.js with the MinChat Provider passing our API key and the current user that is chatting:

import React from "react";
import ReactDOM from "react-dom/client";
import reportWebVitals from "./reportWebVitals";
import App from "./App";
import { MinChatProvider } from "@minchat/react";

const root = ReactDOM.createRoot(document.getElementById("root"));

const firstUser = {
  id: "micheal",
  name: "Micheal Saunders",
};

root.render(
  <React.StrictMode>
    <MinChatProvider apiKey={906373408} user={firstUser}>
      <App />
    </MinChatProvider>
  </React.StrictMode>
);

reportWebVitals();

In Our App.js file we import the useMinChat() hook to access the minchat object and start a new conversation with the second user using the useMessages(...) hook.

Our App.js file now looks like this:

import styles from "@chatscope/chat-ui-kit-styles/dist/default/styles.min.css";
import { MainContainer, ChatContainer, MessageList,Message,MessageInput} from "@chatscope/chat-ui-kit-react";
import { useMinChat, useMessages } from "@minchat/react";

const secondUser = {
  id: "mercy",
  name: "Mercy Wells",
};

function App() {
  const minchat = useMinChat();

  const chat = minchat.chat(secondUser);

  const { messages, sendMessage } = useMessages(chat);

  return (
    <div style={{ position: "relative", height: "500px", width: "500px" }}>
      <MainContainer>
        <ChatContainer>
          <MessageList>
            <Message
              model={{
                message: "Hello World",
                sender: "Joe",
              }}
            />
          </MessageList>
          <MessageInput placeholder="Type message here" />
        </ChatContainer>
      </MainContainer>
    </div>
  );
}

export default App;

Step 3: Connecting everything together

We now want to be able to send messages and receive them as well as view messages that are sent and received in our react chat app,

We are going to update the MessageInput react chat component to be able to send the messages when submitted:

<MessageInput
  onSend={(_, textContent) => sendMessage({ text: textContent })}
  placeholder="Type message here"
/>

We then want the messages to appear in the message list in real time making sure to differentiate messages that are sent by the first user (who is our current user) and the second user:

<MessageList>
  {messages &&
    messages.map((message) => {
      return message.user.id === "mercy" ? (
        <Message
          model={{
            message: message.text,
            sender: message.user.name,
          }}
        />
      ) : (
        <div style={{ justifyContent: "flex-end", display: "flex" }}>
          <Message
            model={{
              message: message.text,
              sender: message.user.name,
            }}
          />
        </div>
      );
    })}
</MessageList>

The App.js file should now look like this:

import styles from "@chatscope/chat-ui-kit-styles/dist/default/styles.min.css";
import { MainContainer, ChatContainer, MessageList,Message,MessageInput} from "@chatscope/chat-ui-kit-react";
import { useMinChat, useMessages } from "@minchat/react";

const secondUser = {
  id: "mercy",
  name: "Mercy Wells",
};

function App() {
  const minchat = useMinChat();

  const chat = minchat.chat(secondUser);

  const { messages, sendMessage } = useMessages(chat);
  return (
    <div style={{ position: "relative", height: "500px", width: "500px" }}>
      <MainContainer>
        <ChatContainer>
          <MessageList>
            {messages &&
              messages.map((message) => {
                return message.user.id === "mercy" ? (
                  <Message
                    model={{
                      message: message.text,
                      sender: message.user.name,
                    }}
                  />
                ) : (
                  <div style={{ justifyContent: "flex-end", display: "flex" }}>
                    <Message
                      model={{
                        message: message.text,
                        sender: message.user.name,
                      }}
                    />
                  </div>
                );
              })}
          </MessageList>
          <MessageInput
            onSend={(_, textContent) => sendMessage({ text: textContent })}
            placeholder="Type message here"
          />
        </ChatContainer>
      </MainContainer>
    </div>
  );
}

export default App;

Your react chat app is now complete with in app chat functionality.

You can take this a step further by creating a second react chat component which swaps the first user and second user and

then have real-time communication and responses between the two. View the MinChat docs and be able to create loading states,error states, view online, typing indicator, etc.

Conclusion

In conclusion, this tutorial walks through the process of building a react chat application using the MinChat Chat SDK.

The tutorial begins by explaining the concept of react chat components and how to break down the chat UI into individual react chat components.

The tutorial then shows how to install and use the Chat UI Kit React library to create the chat UI, and provides code examples for each step along the way. By following the steps in this tutorial, you will be able to create a fully functional react chat application that you can customize and use as you like.

MinChat is a great Chat API service that enables you to build in app chat functionality without worrying about building a backend or all the complexities involved in building real-time communication features.

Tutorial is an extract from this article.


Written by mundiazm | Founder minchat.io ,an api that enables you to build chat functionality into your app or website within minutes
Published by HackerNoon on 2022/12/29