Let's build a React Native Chat App to connect with Users & Groups, make Audio & Video Calls, send Text, Media Messages, and more.
To simplify the process and have a production-ready solution in a few minutes, we will use CometChat React Native UI Kit.
Before you begin, ensure you have met the following requirements:
- A text editor. (e.g., Visual Studio Code, Notepad++, Sublime Text, Atom, or VIM)
- React Native environment setup either iOS/Android.
I have to admit that one of my always wanted to build projects was a Chat App with Video Calls using React Native, and thanks to CometChat, that dream is now a reality, and you will fulfill the same today by following the steps of this guide.
We all know the difficulties of building an MVP or integrating Video Calls/Chat into an existing React Native project. There're a lot of things to take into consideration, especially when using Video Calls. Thanks to CometChat UI Kit, we can build such functionalities in a matter of minutes.
First, you need to register on CometChat. Click here to Sign Up. Then you can create a New App based on your location. You can also choose CometChat API v2 or the most recent one, which is v3. For this guide, we will choose v3.
Once you create your new CometChat app, you will see the list of apps with essential information like APP ID, Region, and Version. We will use that information later when we initialize our React Native app with CometChat SDK.
Click on the recently created app to see more information.
Create your React Native App
Open your terminal, and using npx, let's create our React Native Chat App. For this post, we will use React Native v0.64; I strongly recommend you to use the same version to avoid compatibility issues with the libraries we will use.
Now, open chatApp using your favourite IDE/Text Editor; I will choose Visual Studio Code and also let's create a src folder in the root of our app. Move the file App.js from the root into src folder, remember to update the root index.js to reflect the location change of App.js.
Add CometChat Dependency
Open your terminal, and let's add CometChat Pro v3 package for React Native.
Also, we need to add React Native Async Storage.
Setup for iOS
For iOS, we only need to install the dependencies using Cocoa Pods for that you run npx pod-install and should be good to go.
Setup for Android
Now, for Android, we need to make a couple of adjustments. First, open android/build.gradle file, and we will update the buildScript.
And inside allProjects add maven configuration for cometchat-prop-android.
Initialize CometChat Inside your App
First, let's create a constants.js file in the root of our app with an object that we will export that contains our CometChat App APP_ID, REGION, and AUTH_KEY. Go into CometChat Dashboard and replace the values with your app settings.
Now, let's move into our app entrance file generally is recommended to use ./index.js file.
Once we finish setting our app and calling the init() method, we can test if everything runs fine. For that, we're going to use Simulators. If you're a Mac user, you can try both iPhone & Android simulators; otherwise, only the Android Simulator will work for you.
Open a terminal and run the Simulator for iOS:
You should see the iPhone Simulator with the console.warn message we used inside the init() method if everything goes well.
For Android run.
The result should be the same as the iPhone Simulator.
CometChat UI Kit
Next, let's clone CometChat React Native UI Kit repository on our local computer. Open a new terminal window and clone the following repository in another location. In my case, I will clone it in my Desktop folder:
Once you clone the UI Kit repository, let's create a new folder in the root of our app with the name of cometchat-pro-react-native-ui-kit and copy and paste all the folders and files we have inside the cloned repository cometchat-pro-react-native-ui-kit/src folder into our just created folder.
CometChat UI Kit Dependencies
To make the UI Kit work, we need to install a list of dependencies. And to make the process more petite prom to issues, I will give the list of dependencies that you will establish with the same version; otherwise, you probably will have problems.
Now, copy the list from above and replace it with the dependencies list you have in your package.json file in the app's root.
Now, let's remove the node_modules & the package-lock.json file and install all the dependencies one more time.
Have in mind that some of this libraries needs an extra step in order to finish the installation process for example:
- react-navigation (Android)
- react-native-vector-icons (iOS & Android)
- react-native-video (Android)
- react-native-image-picker (iOS)
For iOS must of the setup is done by using Cocoa Pods. Let's start there and run npx pod-install.
And for Android, let's finish the react-navigation setup process, by opening the file android/app/src/main/java/com/chatapp/MainActivity.java and this is mostly because of the react-navigation version we use for this guide which is v5.X.
For react-native-vector-icons we need to add the list of Fonts into the Info.plist file for iOS.
And for Android we need to update android/app/build.gradle file adding the next line
apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"
For react-native-video we need to open the android/build.gradle file and add jcenter() inside allprojects > repositories section.
iOS Configuration for react-native-image-picker
We need to add the appropriate keys to your Info.plist. If you are allowing user to select image/video from photos, add NSPhotoLibraryUsageDescription.
If you are allowing user to capture image add NSCameraUsageDescription key also.
If you are allowing user to capture video add NSCameraUsageDescription add NSMicrophoneUsageDescription key also.
Remember that we used specific versions of the libraries, and I recommend you use the identical versions I used. If you still want to try the latest versions, you're free to do it. I hope you won't find too many issues 😉
To allow a user to use CometChat, the user must log in to CometChat. CometChat does not handle user management. You must handle user registration and login at your end. Once the user is logged into your app/site, you can log in the user to CometChat programmatically. So the user does not ever directly login to CometChat.
For this App, we will use Firebase to handle the Authentication. Let's install firebase pakage.
Create a new folder inside src called screens, and inside screens folder, let's create Login & SignUp folders and inside each folder add an index.js file.
Your files & folders should look like this
Inside src/screens/SignUp/index.js copy & paste next code:
Let's add some styles for our screens; for that, create a styles folder and add an index.js file.
Inside src/screens/Login/index.js copy & paste next code:
We use navigation prop from react-navigation to navigate to the SignUp screen, we still haven't created our Stack Navigation yet, but we will. Just keep reading.
As I mentioned before, we will use firebase authentication to handle the authentication process. To do that, we need to navigate into firebase.com, sign up and create a new firebase app.
Once you have your firebase app, let's select web to add Firebase to our app.
At then end you should see the Firebase SDK credentials for your project.
Let's move into the next step in order to setup firebase SDK in our App. Create a new file inside src folder and name it firebase.js.
Now, let's move back to our firebase app and activate the Authentication process for Email/Password. Click Authentication and then click Get started.
Select Email/Password and then Enable the service. Lastly, click Save.
Open our SignUp screen and add the next lines of code:
We use the gravatar-api package for the avatar image URL, which will create a Gravatar based on the user email. We need to install it, so run the following command:
Also, we import a couple of files and functions like createUserWithEmailAndPassword, updateProfile, signInWithEmailAndPassword from firebase/auth in order to register a new user and then once is registered we update the displayName and photoURL fields. Keep in mind that we need to pass our firebase app configuration to createUserWithEmailAndPassword, updateProfile & signInWithEmailAndPassword, and because of that we also imported firebaseAuth from our firebase local configuration.
In the end we perform these actions:
- Sign Up
- Update Profile
- Sign In
User LogIn Screen
Inside src/screens/Login/index.js copy & paste next code:
Now for the Login process, we use signInWithEmailAndPassword from firebase/auth and similar to the SignUp process we also need to pass the local firebase configuration as parameter.
We have already installed react-navigation. Let's create Stack navigation to navigate between our two new screens.
Create an index.js file inside screens folder.
Open our App.js file and update the content adding a NavigationContainer and importing our screens/index.js file to render our screens.
Let's run what we have now using the Simulator, for iOS use npx react-native run-ios & for Android npx react-native run-android.
Note: If you had the Simulator running, I recommend you stop it and rerun the App because we installed quite a good amount of packages.
Go ahead and test the app by registering a new user using email & password. You should see your new user inside the firebase authentication dashboard if everything is OK, similar to the image below.
We already test the Sign Up & LogIn process. We need to keep the user logged-in in our app and navigate into the other CometChatUI functionalities we have when using the React Native UI Kit.
To make that, we will use React Context API and create a Firebase Provider. Inside the src folder, let's create a context folder and inside add a new file named FirebaseContext.js
Similar to Firebase we will create a CometChatAuthContext Provider. Create a new file named /context/CometChatAuthContext.js
We created an Firebase & CometChat Provider similar to a Redux where we have a reducer function, an initialState and actions that will modify the state. It is identical to the use of React-Redux, but instead of spending too much time following Redux's implementation, we will go this way.
Now, let's import both Providers and use it inside our App.js file:
Now we can consume both Firebase & CometChat Providers inside our app. Let's dispatch some actions when the user SignUp and when the user LogIn into our app. We're going to register the user into CometChat when they Sign Up.
First, the user will be registered to Firebase. Second, the user will be registered to CometChat. Third, the user will Sign In to Firebase.
Please read the comments inside the code above for an understanding of what we added and why.
The idea here is to use Firebase Authentication data to Register/SignIn the user into CometChat. And for that, we need some information from the user like the UID, Name, and Avatar.
With that information, we can use @cometchat-pro/react-native-chat package to Create & Sign In the user into CometChat API.
We also need to update our MainScreens logic inside screens/index.js to show <AuthScreens /> or <HomeScreen /> based on user authentication.
Note: Before you continue, the App will probably crash if you are still running it with the Simulator after adding the changes below. You can re-rerun the App later.
As you can see, we added a couple of new screens (that don't exist yet) and also added a new Stack Navigator. Then we added some logic for subscribing to the onAuthStateChanged function from Firebase to check the authentication state changes and retrieve the user information and accessToken. Based on the accessToken, we show either <HomeScreen /> or <AuthScreens />.
Let's add the new screens:
Finally, you should test the Firebase Authentication process for Login/LogOut/SignUp users.
Feel free to run the app on the simulator. If you have already Signed Up and created the Firebase user, you should log out first and then Sign Up with a different email account. Or you could go into Firebase and remove the previously created user.
Once you Sign Up the new user, you should be redirected into the <HomeScreen />
If everything is OK, you can see the new user information if you Login into cometchat.com account and open the Users section of the Dashboard. When you create an App, it also comes with a couple of Super Heros users that you can use for testing.
Once we finish with the authentication, finally, we can jump right into CometChat Screens. Add a new screen called CometChatScreens inside /screens/CometChatScreens/index.js
Let's add the screen into our MainScreens.
Open /screens/index.js and only update the commented lines. After the next update, we will see the CometCharScreen Sign In button.
Now we can test the CometChat Sign In process. For that run the App in the simulator and navigate into CometChat Screen.
CometChat UI Kit
Now that we have the basic authentication process, let's add a new screen from the CometChat React Native UI Kit to test the complete app with Login and show the CometChatUIScreen.
We added a couple of more screens and an extra Stack.Navigator named CometChatUIScreens will be the screens we will show to the logged-in users.
With this logic in place, if the user is logged-in to CometChat and everything it's OK, you should see <CometChatUIScreens /> like in the image below.
LogOut Users from CometChat
We're missing the LogOut functionality in our app, let's add it inside CometChatUserProfile component. CometChatUserProfile is one of the UI Kit components. Open the file cometchat-pro-react-native-ui-kit/components/UserProfile/CometChatUserProfile/index.js. We will combine our logic with the existing UI Kit component.
If everything is ok, you should see the new Logout feature inside the CometChatUserProfile component.
Testing the Chat App
And the final step is to test the app using an actual device, either iPhone/Android. In my case, I'm using two iPhones to try it (iPhone SE & iPhone 12). To test using iPhones, you need to have an Apple Developer account and Xcode downloaded.
Inside our project, you will find the Xcode Workspace file inside ios/chatApp.xcworkspace; double click that file to open Xcode. Remember that we're using Cocoa Pods for installing and linking our iOS libraries' dependencies; for that reason, when you open Xcode, you should open the Workspace file.
You will need to select the Signing & Capabilities tab to choose your Apple Development account inside the Team dropdown. Also, make sure you have the Checkbox Automatically manage signing active. If you can´t see your Apple Development account, you need to add your Account in Xcode. For that, go to Xcode > Preferences and inside Account add your Apple Development account.
And one more thing, if you want to install the App in release mode, you can do it directly from Xcode too. Just select Product > Scheme > Edit scheme and then choose release.
And finally you just hit the Play button.
In conclusion, we have done an amazing job in developing a chat applictaion for Android and iOS by leveraging React Native, Firebase, and CometChat React Native UI Kit.
You have seen how to build most of the chat functionalities such as real-time messaging using CometChat. I hope you enjoyed this tutorial and that you were able to successfully build your React Native chat app. Jump into the comments and let me know your experience.
About the Author