DEV Community

Cover image for Build Privex: A Cross-Platform ReactNative Chat App
Gospel Darlington
Gospel Darlington

Posted on

Build Privex: A Cross-Platform ReactNative Chat App

What you’ll be building. See live demo and Git Repo Here.

Privex Chat Interface

Introduction

Let’s be real, if you haven’t built a chat app yet, you are still a little bit behind the cutting edge of software development. You need to upskill your app development to the next level. Luckily, cross-platform frameworks such as ReactNative can get you building a modern chat app in no time like the one seen above.

In this tutorial, you will learn how to use; ReactNative, CometChat, and Firebase to build a one-on-one chat app with a stunning UI.

If you are ready, let’s get started…

Prerequisite

To understand this tutorial, you should already be familiar with ReactNative; the rest of the stacks are simple to grasp. The packages used to create this application are listed below.

Installing The Project Dependencies

First, download and install NodeJs on your machine. Then, if you haven't already, go to their website and finish the installation. The Expo-CLI must then be installed on your computer using the command below. You can get to their doc page by clicking on this LINK.

# Install Expo-CLI
npm install --global expo-cli
Enter fullscreen mode Exit fullscreen mode

After that, open the terminal and create a new expo project called privex, selecting the blank template when prompted. Use the example below to demonstrate this.

#Create a new expo project and navigate to the directory
expo init privex
cd privex

#Start the newly created expo project
expo start
Enter fullscreen mode Exit fullscreen mode

Running the above commands on the terminal will create a new react-native project and start it up on the browser. Now you will have the option of launching the IOS, Android, or the Web interface by simply selecting the one that you want. To spin up the development server on IOS or Android you will need a simulator for that, use the instruction found here to use an IOS or Android simulator, otherwise, use the web interface and follow up the tutorial.

Great, now follow the instructions below to install these critical dependencies for our project. Yarn is the expo's default package manager; see the codes below.

# Install the native react navigation libraries
yarn add @react-navigation/native
yarn add @react-navigation/native-stack

#Installing dependencies into an Expo managed project
expo install react-native-screens react-native-safe-area-context react-native-gesture-handler

# Install an Icon pack and a state manager
yarn add react-native-vector-icons react-hooks-global-state
Enter fullscreen mode Exit fullscreen mode

Nice, now let’s set up Firebase for this project.

Setting Up Firebase

Run the command below to properly install firebase in the project.

#Install firebase with the command
expo install firebase
Enter fullscreen mode Exit fullscreen mode

Let's get started by configuring the Firebase console for this project, including the services we'll be using.

If you do not already have a Firebase account, create one for yourself. After that, go to Firebase and create a new project called privex, then activate the Google authentication service, as detailed below.

Step 1

Step 2
Project Creation Process
Step 3

Firebase supports authentication via a variety of providers. For example, social authentication, phone numbers, and the traditional email and password method. Because we'll be using the Google authentication in this tutorial, we'll need to enable it for the project we created in Firebase, as it's disabled by default. Click the sign-in method under the authentication tab for your project, and you should see a list of providers currently supported by Firebase.

Firebase Authentication Service

Step 1
Step 2
Step 3

Super, that will be all for the firebase authentication, lets generate the Firebase SDK configuration keys.

You need to go and register your application under your Firebase project.

Project Overview Page

On the project’s overview page, select the add app option and pick web as the platform.

Registering a Firebase SDK Step 1
Registering a Firebase SDK Step 2

Return to the project overview page after completing the SDK config registration, as shown in the image below.

Project overview page

Now you click on the project settings to copy your SDK configuration setups.

Project Setups

The configuration keys shown in the image above must be copied to a separate file that will be used later in this project.

Create a file called firebase.js in the root of this project and paste the following codes into it before saving.

You are awesome if you followed everything correctly. We'll do something similar for CometChat next.

Setting CometChat

Head to CometChat and signup if you don’t have an account with them. Next, log in and you will be presented with the screen below.

CometChat Dashboard

To create a new app, click the Add New App button. You will be presented with a modal where you can enter the app details. The image below shows an example.

Add New App Modal

Following the creation of your app, you will be directed to your dashboard, which should look something like this.

API Key Here
Rest API Key Here

You must also copy those keys to a separate file in the manner described below. Simply create a file called CONSTANTS.js in the project's root directory and paste the code below into it. Now include this file in the .gitIgnore file, which is also located at the root of this project; this will ensure that it is not published online.

export const CONSTANTS = {
  APP_ID: 'xxx-xxx-xxx',
  REGION: 'us',
  Auth_Key: 'xxx-xxx-xxx-xxx-xxx-xxx-xxx-xxx',
}
Enter fullscreen mode Exit fullscreen mode

Finally, delete the preloaded users, and groups as shown in the images below.

Users List
Group List

Awesome, that will be enough for the setups, let’s start integrating them all into our application, we will start with the components.

The Components Directory

This project contains several directories; let's begin with the components folder. Within the root of this project, create a folder called components. Let's begin with the Header component.

The Header Component

The Header Component

This is a styled component supporting the beauty of our app. Within it is the avatar element which displays the current user's profile picture. Also with this avatar, you can log out from the application. Create this file by going into the components directory and creating a file named HomeHeader.js, afterward, paste the code below into it.

The ChatContainer Component

The Chat Container

This component is responsible for showcasing the recent conversations of a user. It does more than that, it can also display users' stories and a floating button that lunches a modal for showing all the users registered in our app. We will look at each of them separately, shown below is the code for it.

The FloatingButton Component

FloatingButton

This component is responsible for launching the UserList modal which allows us to chat with a new user on our platform. Here is the code snippet for it.

The UserList Component

The user List Component

This component is launched by the FloatingButton. It displays all the users that are on our platform and enables you to have a first-time conversation with them. After then, they can appear in your conversation list. Below is the code responsible for its implementation.

Fantastic, we have just finished building the dedicated components, let’s proceed to craft out the screens now.

The Screens Directory

The screens are similar to website pages; each screen represents a page, and you can navigate from one to the next using the ReactNative navigator package. Let's proceed with the LoginScreen.

The LoginScreen

The Login Screen

This well-crafted screen does a lot of things behind the scene. It uses Firebase Google authentication to sign you into the system. Once you are signed in, Firebase authStateChange function will take note of you as a logged-in user. This is carried out in the AuthNavigation file. But before you are let into the system, your authenticated details will be retrieved and sent to CometChat either for signing up or signing in. Once CometChat is done, you are then let into the system. See the code below for a full breakdown.

The HomeScreen

The Home Screen

This well-crafted screen brings together all the dedicated components in the components directory to one space. Each of the components knows how to perform their duties. Not many words here, let the code below do all the explaining.

import { SafeAreaView, StyleSheet } from 'react-native'
import ChatContainer from '../components/ChatContainer'
import FloatingButton from '../components/FloatingButton'
import HomeHeader from '../components/HomeHeader'
import UserList from '../components/UserList'
const HomeScreen = ({ navigation }) => {
  return (
    <SafeAreaView style={styles.container}>
      <HomeHeader />
      <ChatContainer navigation={navigation} />
      <FloatingButton />
      <UserList navigation={navigation} />
    </SafeAreaView>
  )
}
export default HomeScreen
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#122643',
  },
})
Enter fullscreen mode Exit fullscreen mode

The ChatScreen

The Chat Screen

Lastly for the screens, we have the chat screen that lets us perform one-on-one conversations with another user. It heavily uses the CometChat SDK for its operations, let's take a look at the function of the code.

There are three functions you should take note of, they are the meat of this screen. The getMessages, sendMessage, and listenForMessage functions. They utilize the CometChat SDK and each one of them performs their operations according to their names.

That’s the last screen for the application, let’s seal it up with the App component and the router set up…

Setting Up The Router

Now that we've finished coding the project, let's set up the navigation routers and guards. To do so, create and paste the following codes as directed below.

The Navigation file
This categorizes the screens into two groups: those that require authentication and those that do not.
Make a new file called "navigation.js" in the project's root and paste the code below into it.

The AuthNavigation file
This file displays screens logically to you based on the authState of the firebase authentication service. It is also responsible for signing a user to CometChat depending on whether they are registering or logging in into the system. To proceed, create a new file in the project's root called AuthNavigation.js and paste the code below into it.

Finally, the App component…

The App Component
This component puts together every part of this project. Please replace the content of this file with the code below.

import { CometChat } from '@cometchat-pro/react-native-chat'
import { useEffect } from 'react'
import AuthNavigation from './AuthNavigation'
import { CONSTANTS } from './CONSTANTS'
export default function App() {
  const initCometChat = () => {
    let appID = CONSTANTS.APP_ID
    let region = CONSTANTS.REGION
    let appSetting = new CometChat.AppSettingsBuilder()
      .subscribePresenceForAllUsers()
      .setRegion(region)
      .build()
    CometChat.init(appID, appSetting)
      .then(() => console.log('Initialization completed successfully'))
      .catch((error) => console.log('Initialization failed with error:', error))
  }
  useEffect(() => initCometChat(), [])
  return <AuthNavigation />
}
Enter fullscreen mode Exit fullscreen mode

Cheers, you just smashed this app now it’s time you do more than this with this new trick you’ve learned.

You can spin up your server using the code below on your terminal if you have not done that already.

# Start your ReactNative local server on the web view
yarn web
Enter fullscreen mode Exit fullscreen mode

The App should function like the one in the image below.

The App Overview

Conclusion

We've reached the end of this tutorial; hopefully, you learned something new. Becoming a modern-day developer can be difficult, but it is not impossible; you can accomplish more than you think; all you need is a little guidance. And now you know how to use ReactNative, Firebase, and CometChat to create a fantastic chat app with a beautiful interface. I have more of these tutorials that will show you how to make a private or public group chat. I'm excited to see your magnificent creations.

All the best!

About the Author

Gospel Darlington kick-started his journey as a software engineer in 2016. Over the years, he has grown full-blown skills in JavaScript stacks such as React, ReactNative, VueJs, and more.

He is currently freelancing, building apps for clients, and writing technical tutorials teaching others how to do what he does.

Gospel Darlington is open and available to hear from you. You can reach him on LinkedIn, Facebook, Github, or on his website.

Top comments (0)