Integrating Firebase with React Native

Published on Dec 5, 2018

10 min read

REACT

This post has been updated in 2021. Please visit this URL to view the new post.

Firebase is a Backend as a Service (BaaS) that provides an advantage to mobile developers who use React Native for developing mobile applications. As a React Native developer, by using Firebase you can start building an MVP (minimum viable product), keeping the costs low and prototyping the application pretty fast. In this tutorial, we will be learning how to get started by integrating Firebase with a React Native application. We will also create a small application from scratch with the help of Firebase & React Native to see how they work together.

Getting Started

🔗

Firebase is a platform that got acquired by Google and has a healthy and active community. Most users in this community are web and mobile developers as Firebase can help with mobile analytics, push notification, crash reporting and out of the box provides email as well as social authentication.

To get started, you will need a target mobile OS, whether you choose to go with iOS or Android or both. Please refer to React Native official documentation if you are setting up React Native development environment for the first time. You will need sdk tools and Android Studio especially to setup a developer environment for Android. For iOS, you only need Xcode installed on your macOS. You will also need to have installed:

  • Nodejs (>= 8.x.x) and npm/yarn installed
  • react-native-cli (>= 2.0.1)

React Native is distributed as two npm packages, react-native-cli, and react-native. We are going to use the react-native-cli to generate an app. Begin by installing react-native-cli:

npm install -s react-native-cli

Now, let’s create a new React Native project called “rnFirebaseDemo”:

react-native init rnFirebaseDemo

When the above command is done running, traverse into the project directory using cd rnFirebaseDemo. Now, let’s check if everything is working correctly and our React Native application has been properly initialized by running one of the following commands:

# on macOS
react-native run-ios
# For Windows/Unix users
react-native run-android

This command will run the default screen as shown below in an iOS simulator or Android emulator but it will take a few moments since we are running it for the first time.

ss1

Adding Firebase

🔗

To add Firebase to our existing React Native application, we need to install the dependency.

yarn add firebase

When we open the project in a code editor, its structure looks like this:

ss2

We need to make some modifications before we can really start building our app. Create an src directory inside the root folder. This is where our app components and screens will live. Further, within the src directory, we will create two folders: screens and components.

ss3

The screen directory will contain all the UI related components that we need to display to the end user, whereas the components folder will contain any other component that will be used or re-used to display the user interface.

Let us create our first screen, Home screen, inside screens/ with a new file Home.js.

1import React, { Component } from 'react';
2import { View, Text } from 'react-native';
3
4export default class Home extends Component {
5 render() {
6 return (
7 <View>
8 <Text>Home Screen</Text>
9 </View>
10 );
11 }
12}

Our next screen is going to be Add Item. Create a new file called AddItem.js.

1import React, { Component } from 'react';
2import { View, Text } from 'react-native';
3
4export default class AddItem extends Component {
5 render() {
6 return (
7 <View>
8 <Text>Add Item</Text>
9 </View>
10 );
11 }
12}

Our last screen is going to be a List of items that we need to display. In the same directory, create a new file called List.js.

1import React, { Component } from 'react';
2import { View, Text } from 'react-native';
3
4export default class List extends Component {
5 render() {
6 return (
7 <View>
8 <Text>List</Text>
9 </View>
10 );
11 }
12}

Adding react-navigation

🔗

To navigate between different screens, we need to add the react-navigation library. We are going to use the latest version that is 3.0.0.

yarn add react-navigation

Next, we will install react-native-gesture-handler. If you’re using Expo, you don’t need to do anything here.

yarn add react-native-gesture-handler

The next step is clearly to run the command below and link the libraries we just installed:

react-native link

After adding this package, let us run the build process again:

# on macOS
react-native run-ios
# For Windows/Unix users
react-native run-android

Now, to see it in action, let us add the Home component as our first screen. Add the following code in App.js.

1import React, { Component } from 'react';
2import { createStackNavigator, createAppContainer } from 'react-navigation';
3import Home from './src/screens/Home';
4
5// we will use these two screens later in our AppNavigator
6import AddItem from './src/screens/AddItem';
7import List from './src/screens/List';
8
9const AppNavigator = createStackNavigator({
10 Home: {
11 screen: Home
12 }
13});
14
15const AppContainer = createAppContainer(AppNavigator);
16
17export default class App extends Component {
18 render() {
19 return <AppContainer />;
20 }
21}

At this stage, if we go to the simulator, we will see the following result:

ss4

The Home Screen is showing up. We will add two other screens as routes to AppNavigator in order to navigate to them through the Home Screen.

1const AppNavigator = createStackNavigator(
2 {
3 Home,
4 AddItem,
5 List
6 },
7 {
8 initialRouteName: 'Home'
9 }
10);

Now, our stack has three routes: a Home route, an AddItem route, and a ListItem route. The Home route corresponds to the Home screen component, the AddItem corresponds to the AddItem screen and the ListItem route corresponds to the ListItem component. The initial route for the stack is the Home route, this is defined if we have multiple screens and need to describe a starting point.

Navigating between the screens

🔗

Previously, we defined a stack navigator with three routes but we didn't hook them up in order to navigate between them. Well, this is an easy task too. The react-navigation library provides us with a way to manage navigation from one screen to another and back. To make this work, we will modify the Home.js.

1import React, { Component } from 'react';
2import { Button, View, Text } from 'react-native';
3
4export default class Home extends Component {
5 render() {
6 return (
7 <View>
8 <Text>Home Screen</Text>
9 <Button
10 title="Add an Item"
11 onPress={() => this.props.navigation.navigate('AddItem')}
12 />
13 <Button
14 title="List of Items"
15 color="green"
16 onPress={() => this.props.navigation.navigate('List')}
17 />
18 </View>
19 );
20 }
21}

In the code above, we are adding a Button component from the react-native API. react-navigation passes a navigation prop in the form of this.props.navigation to every screen in the stack navigator. We have to use the same screen name on the onPress function to navigate as we defined in App.js under AppNavigator.

You can also customize the back button manually with your own styling on both screens AddItem and List but, for our demonstration, we are going to use the default.

ss5

Creating a Database with Firebase

🔗

Go to the Firebase Console, log in from your Google Account and a create a new project.

ss6

We will then add the database configuration in a new file inside src/config.js.

1import Firebase from 'firebase';
2let config = {
3 apiKey: 'AIzaXXXXXXXXXXXXXXXXXXXXXXX',
4 authDomain: 'rnfirebXXX-XXXX.firebaseapp.com',
5 databaseURL: 'rnfirebXXX-XXXX.firebaseapp.com',
6 projectId: 'rnfirebase-XXXX',
7 storageBucket: 'rnfirebase-XXXX.appspot.com',
8 messagingSenderId: 'XXXXXXX'
9};
10let app = Firebase.initializeApp(config);
11export const db = app.database();

The config object is where you fill in the details you get after creating a new project in Firebase and going to the section Add Firebase to your web app. Also in the Firebase console, from left sidebar, click on Database and then choose the first option: ((Realtime Database)). Then, go to “rules” and paste the following:

1{ "rules": { ".read": true, ".write": true } }

ss7

Adding Data from the App to Firebase

🔗

In this section, we will edit AddItem.js which represents an input field and a button. The user can add a item to the list and it will get saved to Firebase data.

1import React, { Component } from 'react';
2import {
3 View,
4 Text,
5 TouchableHighlight,
6 StyleSheet,
7 TextInput,
8 AlertIOS
9} from 'react-native';
10
11import { db } from '../config';
12
13let addItem = item => {
14 db.ref('/items').push({
15 name: item
16 });
17};
18
19export default class AddItem extends Component {
20 state = {
21 name: ''
22 };
23
24 handleChange = e => {
25 this.setState({
26 name: e.nativeEvent.text
27 });
28 };
29 handleSubmit = () => {
30 addItem(this.state.name);
31 AlertIOS.alert('Item saved successfully');
32 };
33
34 render() {
35 return (
36 <View style={styles.main}>
37 <Text style={styles.title}>Add Item</Text>
38 <TextInput style={styles.itemInput} onChange={this.handleChange} />
39 <TouchableHighlight
40 style={styles.button}
41 underlayColor="white"
42 onPress={this.handleSubmit}
43 >
44 <Text style={styles.buttonText}>Add</Text>
45 </TouchableHighlight>
46 </View>
47 );
48 }
49}
50
51const styles = StyleSheet.create({
52 main: {
53 flex: 1,
54 padding: 30,
55 flexDirection: 'column',
56 justifyContent: 'center',
57 backgroundColor: '#6565fc'
58 },
59 title: {
60 marginBottom: 20,
61 fontSize: 25,
62 textAlign: 'center'
63 },
64 itemInput: {
65 height: 50,
66 padding: 4,
67 marginRight: 5,
68 fontSize: 23,
69 borderWidth: 1,
70 borderColor: 'white',
71 borderRadius: 8,
72 color: 'white'
73 },
74 buttonText: {
75 fontSize: 18,
76 color: '#111',
77 alignSelf: 'center'
78 },
79 button: {
80 height: 45,
81 flexDirection: 'row',
82 backgroundColor: 'white',
83 borderColor: 'white',
84 borderWidth: 1,
85 borderRadius: 8,
86 marginBottom: 10,
87 marginTop: 10,
88 alignSelf: 'stretch',
89 justifyContent: 'center'
90 }
91});

In the code above, we are adding a Firebase database instance from config.js and db and then pushing any item that the user adds through addItem and handleSubmit(). You will get an alert message when you press the button Add to add the item from the input value as shown below.

ss8

To verify that the data is there in the database, go to your Firebase console.

ss9

Fetching Items from the Database

🔗

To fetch data from the Firebase database, we are going to use the same reference to db in List.js.

1import React, { Component } from 'react';
2import { View, Text, StyleSheet } from 'react-native';
3import ItemComponent from '../components/ItemComponent';
4
5import { db } from '../config';
6
7let itemsRef = db.ref('/items');
8
9export default class List extends Component {
10 state = {
11 items: []
12 };
13
14 componentDidMount() {
15 itemsRef.on('value', snapshot => {
16 let data = snapshot.val();
17 let items = Object.values(data);
18 this.setState({ items });
19 });
20 }
21
22 render() {
23 return (
24 <View style={styles.container}>
25 {this.state.items.length > 0 ? (
26 <ItemComponent items={this.state.items} />
27 ) : (
28 <Text>No items</Text>
29 )}
30 </View>
31 );
32 }
33}
34
35const styles = StyleSheet.create({
36 container: {
37 flex: 1,
38 justifyContent: 'center',
39 backgroundColor: '#ebebeb'
40 }
41});

For the ItemComponent, we create a new file inside components/ItemComponent.js. This is a non-screen component. Only the List will use it to map and display each item.

1import React, { Component } from 'react';
2import { View, Text, StyleSheet } from 'react-native';
3import PropTypes from 'prop-types';
4
5export default class ItemComponent extends Component {
6 static propTypes = {
7 items: PropTypes.array.isRequired
8 };
9
10 render() {
11 return (
12 <View style={styles.itemsList}>
13 {this.props.items.map((item, index) => {
14 return (
15 <View key={index}>
16 <Text style={styles.itemtext}>{item.name}</Text>
17 </View>
18 );
19 })}
20 </View>
21 );
22 }
23}
24
25const styles = StyleSheet.create({
26 itemsList: {
27 flex: 1,
28 flexDirection: 'column',
29 justifyContent: 'space-around'
30 },
31 itemtext: {
32 fontSize: 24,
33 fontWeight: 'bold',
34 textAlign: 'center'
35 }
36});

This step concludes the integration of a Firebase database with our React Native app. You can now add the new data items and fetch them from the database as shown below.

ss9

Conclusion

🔗

In this tutorial, we’ve shown you how to integrate Firebase with a React Native application. You don’t a complete server that creates an API and further uses a database to prototype or build an MVP of your application.

You can find the complete code inside this Github repo.

Originally published at Jscrambler


More Posts

Browse all posts

Aman Mittal author

I'm a software developer and a technical writer. In this blog, I write about Technical writing, Node.js, React Native and Expo.

Currently, working at Expo. Previously, I've worked as a Developer Advocate, and Senior Content Developer with companies like Draftbit, Vercel and Crowdbotics.


Copyright ©  2019-2022 Aman Mittal · All Rights Reserved.