Building a Chat Application with React Native and Firebase
Building a Chat App with React Native can be a fun and rewarding project. In this blog post, we will guide you through the steps of building a chat application with React Native and Firebase.
React Native is a popular JavaScript framework for building mobile applications. It allows developers to write code once and deploy it on both iOS and Android platforms. Firebase, on the other hand, is a cloud-based service that provides a variety of tools and services for building mobile and web applications.
Let’s get started!
Prerequisites
Before we begin, you need to have the following:
- Node.js installed on your computer
- A Firebase account
- A basic understanding of React Native and JavaScript
Creating a new Chat App with React Native
First, we need to create a new React Native project. To do this, run the following command in your terminal:
npx react-native init ChatApp
This will create a new React Native project called “ChatApp” in your current directory.
Next, navigate into the project directory by running:
cd ChatApp
Installing dependencies
We need to install a few dependencies to get started. Run the following command in your terminal:
npm install @react-navigation/native @react-navigation/stack firebase
- @react-navigation/native and @react-navigation/stack are navigation libraries for React Native
- firebase is the Firebase SDK for JavaScript
Setting up Firebase
We need to set up Firebase in our project. To do this, follow these steps:
- Go to the Firebase Console and create a new project.
- Click on “Add app” and select “Web” as the platform.
- Register your app by providing a name for your app and a Firebase Hosting subdomain. You can leave the Firebase Hosting subdomain empty if you don’t plan on hosting your app on Firebase.
- Copy the Firebase configuration object that is displayed on the screen.
- Create a new file called firebase.js in your project’s root directory and paste the Firebase configuration object in it.
Your firebase.js file should look something like this:
import firebase from 'firebase/app';
import 'firebase/firestore';
import 'firebase/auth';
const firebaseConfig = {
// Your Firebase configuration object goes here
};
firebase.initializeApp(firebaseConfig);
export default firebase;
Setting up navigation
We need to set up navigation in our app. To do this, create a new file called App.js in your project’s root directory and paste the following code in it:
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import ChatScreen from './screens/ChatScreen';
import LoginScreen from './screens/LoginScreen';
const Stack = createStackNavigator();
export default function App() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="Login" component={LoginScreen} />
<Stack.Screen name="Chat" component={ChatScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}
This code sets up navigation using the @react-navigation/native and @react-navigation/stack libraries. It creates two screens: LoginScreen and ChatScreen.
Creating screens
We need to create two screens: LoginScreen and ChatScreen. To do this, create two new files in a screens directory in your project’s root directory called LoginScreen.js and ChatScreen.js.
In LoginScreen.js, paste the following code:
import React, { useState } from 'react';
import { View, TextInput, Button } from 'react-native';
import firebase from '../firebase';
export default function LoginScreen({ navigation }) {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const handleLogin = () => {
firebase.auth().signInWithEmailAndPassword(email, password)
.then(() => navigation.navigate('Chat'))
.catch(error => alert(error.message));
}
return (
<View>
<TextInput
placeholder= "Email"
value = { email }
onChangeText = { setEmail }
/>
<TextInput
placeholder="Password"
value = { password }
onChangeText = { setPassword }
secureTextEntry = { true}
/>
<Button
title="Login"
onPress = { handleLogin }
/>
</View>
);
}
The handleLogin function uses Firebase’s signInWithEmailAndPassword method to authenticate the user with their email and password. If the authentication is successful, the user is redirected to the ChatScreen. If there is an error, an alert is shown with the error message.
Creating a chat screen
In ChatScreen.js, we will create a chat screen that allows users to send and receive messages. We will use Firebase’s Firestore database to store and retrieve messages.
import React, { useState, useEffect } from 'react';
import { View, Text, TextInput, Button, FlatList } from 'react-native';
import firebase from '../firebase';
export default function ChatScreen() {
const [message, setMessage] = useState('');
const [messages, setMessages] = useState([]);
useEffect(() => {
const unsubscribe = firebase.firestore().collection('messages')
.orderBy('createdAt', 'desc')
.onSnapshot(snapshot => {
const messages = snapshot.docs.map(doc => {
return {
id: doc.id,
...doc.data()
}
});
setMessages(messages);
});
return () => unsubscribe();
}, []);
const handleSend = () => {
firebase.firestore().collection('messages').add({
text: message,
createdAt: firebase.firestore.FieldValue.serverTimestamp()
}).then(() => {
setMessage('');
});
}
const renderMessage = ({ item }) => {
return (
<View style={{ padding: 10 }}>
<Text>{item.text}</Text>
</View>
);
}
return (
<View style={{ flex: 1 }}>
<FlatList
data={messages}
renderItem = {renderMessage}
inverted={true}
/>
<View style={ { flexDirection: 'row' } }>
<TextInput
style={{ flex: 1 }}
placeholder="Type a message"
value={message}
onChangeText={setMessage}
/>
<Button
title="Send"
onPress={handleSend}
/>
</View>
</View>
);
}
The useEffect hook listens for changes in the messages collection in Firestore and updates the messages state whenever there is a change. The renderMessage function renders a single message in the chat. The FlatList component is used to display a list of messages, with the inverted prop set to true to show the latest messages at the bottom.
The handleSend function adds a new message to the messages collection in Firestore with the user’s input text and the current timestamp. The setMessage function is then called to clear the message input field.
Setting up Firebase
Before we can run the chat application, we need to set up Firebase for our project. Follow these steps to set up Firebase:
- Go to the Firebase console (https://console.firebase.google.com/) and create a new project.
- Add a new web app to the project.
- Copy the config object shown on the Firebase web app setup screen.
- Create a new file called firebase.js in the src directory of your React Native project.
- Paste the config object into the firebase.js file and add the following code to initialize Firebase.
This code imports the necessary Firebase modules and initializes Firebase with the config object.
Running the application
To run the chat application, open a terminal window in the project directory and run the following commands:
npm install
npx react-native run-android # or run-ios for iOS
This will install the necessary dependencies and run the application on an Android or iOS device or emulator.
Conclusion
In this tutorial, we have learned how to Chat App with React Native and Firebase. We have created a login screen that authenticates the user with Firebase’s authentication service, and a chat screen that allows users to send and receive messages using Firebase’s Firestore database. We have also set up Firebase for our project and learned how to run the chat application on an Android or iOS device or emulator. With this knowledge, you can now build your own chat application with React Native and Firebase.