Web Programming TutorialsBeginners Guide for Integrating Firebase & React Native In An App

Beginners Guide for Integrating Firebase & React Native In An App

The biggest advantage of using React Native for cross-platform mobile development is, a developer can start building MVP with lower development costs and time by using a solution like Firebase. In this article, we will be learning how to get started by integrating Firebase in a React Native application. We will be creating a small application with the help of Firebase & React Native from scratch to see how they work together.
Firebase is a mobile plus web application development platform that was acquired by Google and has a healthy and active community. Most users in this community are 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. Let us start by creating a new React Native project. I will be using react-native-cli, so make sure you have it already installed using npm in your development environment as a global module. If not, type the following command in your terminal:

npm install -g react-native-cli

To create the project, in the terminal window, type:

react-native init RNFirebaseExample

If the project is successfully initialized, traverse into the project directory using cd RNFirebaseExample. To check, everything is working correctly and our React Native application has been properly initialized run the following command:

react-native run-ios

# For windows users

react-native run-android

To run this command successfully, make sure you have Xcode installed on macOS and you need to run it atleast once. For Windows users, you can install Android Studio by following the instructions from React Native official guide and instead of run-ios type run-android. I will be using run-ios since I am using macOS and for a simulator I will be using iPhone but for android users, you could use android virtual machine and go with the default Nexus emulator device. The complete process slow down once an emulator or a simulator initiates. Once the installation is done, a success message will appear as below.

Firebase installation

Adding Firebase and Initializing Screens

To add Firebase to our existing React Native application, we need to install its dependency:

yarn add firebase

# or

npm install –save firebase

Now let us create the required screens we need for an application to function. First, we will create an src where all the code written for this application will go live. Further, within the src directory, we will create two folders: screens and components. The screen folder will contain all the UI related components that we need to display to the User, whereas the component folder will contain any other component that will be used or re-used to display a UI to the User. In our case, the components directory will contain data from the API.
Our first screen will be a Home Screen. For now, we will display a dummy message within it, screens/home.js:

import React, { Component } from 'react';
import { View, Text } from 'react-native';

export default class Home extends Component {
  render() {
    return (
      <View>
        <Text>Home Screen</Text>
      </View>
    )
  }
}

Our other two screens are going to be AddItem and List. The following is the source code for the other two screens:
AddItem.js:

import React, { Component } from 'react';
import { View, Text } from 'react-native';

export default class AddItem extends Component {
  render() {
    return (
      <View>
        <Text>Add Item</Text>
      </View>
    )
  }
}
List.js:
import React, { Component } from 'react';
import { View, Text } from 'react-native';

export default class List extends Component {
  render() {
    return (
      <View>
        <Text>List</Text>
      </View>
    )
  }
}

Navigating Between Different Screens

In order to navigate the different screens, we created previously, we need to add react-navigation module to our project. This is an open source project that allows us to use a famous way of navigating between the screens or components using Stack based flow. You will notice the same keyword in source code too. First let us install this module:
yarn add react-navigation
After adding this package, I would recommend you to build your application by running react-native run-ios again. After that, open App.js in the root of our project and replace it with the following code:

import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View
} from 'react-native';
import { createStackNavigator } from 'react-navigation';
import Home from './src/screens/Home';
import AddItem from './src/screens/AddItem';
import ListItem from './src/screens/List';

const RootStack = createStackNavigator({
  HomeScreen: Home,
  AddItemScreen: AddItem ,
  ListItemScreen: ListItem
}, {
  initialRouteName: 'HomeScreen',
});

export default class App extends Component {
  render() {
    return (
      <RootStack />
    );
  }
}

To make this work, we will edit our Home.js so that we can navigate both the screens from there. We will use Button component from react-native API. react-navigation passes navigation prop to every screen in stack navigator. We have to use same screen name on onPress function to navigate.

import React, { Component } from 'react';
import { View, Text, Button } from 'react-native';

export default class Home extends Component {
  render() {
    return (
      <View>
        <Text>Go to screen:</Text>
        <Button title='Add an Item' onPress={() => this.props.navigation.navigate('AddItemScreen')}/>
        <Button title='List' onPress={() => this.props.navigation.navigate('ListItemScreen')}/>
      </View>
    )
  }
}

navigating the screen

Creating a Database with Firebase & React Native

Go to Firebase Console, login from your Google Account and a create a new project.

create a database

We will be using the databse configuration as a web application. Inside src create a new file called config.js:

import Firebase from 'firebase';
 let config = {
    apiKey: "",
    authDomain: "",
    databaseURL: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: ""
  };
let app = Firebase.initializeApp(config);
export const db = app.database();

Now, we have to fill the details from the Firebase console. In your console, from left sidebar, click on Database and then choose the first option. Select “Start in test mode” and click on enable.

firebase console

To get the configuration, use the left sidebar and click on Project Overview and then Web Application icon. Copy the configured object and paste it in config.js.

Adding Data

We will edit AddItem.js and it, will create a form such that the user can send the application data to firebase when we connect it with the database.

import React, { Component } from 'react';
import { View, Text, TouchableHighlight, StyleSheet, TextInput,AlertIOS } from 'react-native';

export default class AddItem extends Component {
  state = {
    name: ''
  }

  handleChange = (e) => {
    this.setState({
      name: e.nativeEvent.text
    });
  }
  handleSubmit = () => {
    console.log(this.state.name)
  }


  render() {
    return (
       <View style={styles.main}>
        <Text style={styles.title}>Add Item</Text>
        <TextInput
              style={styles.itemInput}
              onChange={this.handleChange}
            />
        <TouchableHighlight
                style = {styles.button}
                underlayColor= "white"
                onPress = {this.handleSubmit}
              >
              <Text
                  style={styles.buttonText}>
                  Add
              </Text>
            </TouchableHighlight>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  main: {
    flex: 1,
    padding: 30,
    flexDirection: 'column',
    justifyContent: 'center',
    backgroundColor: 'lightgrey'
  },
  title: {
    marginBottom: 20,
    fontSize: 25,
    textAlign: 'center'
  },
  itemInput: {
    height: 50,
    padding: 4,
    marginRight: 5,
    fontSize: 23,
    borderWidth: 1,
    borderColor: 'white',
    borderRadius: 8,
    color: 'white'
  },
  buttonText: {
    fontSize: 18,
    color: '#111',
    alignSelf: 'center'
  },
  button: {
    height: 45,
    flexDirection: 'row',
    backgroundColor:'white',
    borderColor: 'white',
    borderWidth: 1,
    borderRadius: 8,
    marginBottom: 10,
    marginTop: 10,
    alignSelf: 'stretch',
    justifyContent: 'center'
  }
});

Now, we will add Firebase integration to this component so that when a user clickon the button to add an item, that item gets stored in the database. Before we create a component, import and define:

import { db } from '../config';

export const addItem =  (item) => {
    db.ref('/items').push({
        name: item
    });
}

Also, edit the handleSubmit() function to call this reference to database and display an alert message on the screen.

handleSubmit = () => {
      addItem(this.state.name);
      AlertIOS.alert(
        'Item saved successfully'
       );
    }

Adding data

Fetching Items from Database

To fetch data from firebase datastore, we are going to use the same reference to db in List.js:

import React, { Component } from 'react';
import { View, Text, StyleSheet} from 'react-native';
import ItemComponent from '../components/item';

import { db } from '../config';

let itemsRef = db.ref('/items');

const styles = StyleSheet.create({
    container: {
      flex: 1,
      justifyContent: 'center',
      backgroundColor: '#ffffff' 
    }
  })

export default class List extends Component {

    state = {
        items: []
    }

    componentDidMount() {
        itemsRef.on('value', (snapshot) => {
            let data = snapshot.val();
            let items = Object.values(data);
            this.setState({items});
         });
    }
    
    render() {
        return (
            <View style={styles.container}>
                {
                    this.state.items.length > 0
                    ? <ItemComponent items={this.state.items} />
                    : <Text>No items</Text>
                }
            </View>
        )
    }
}

We also make use of components directory as we create a new ItemComponent.js inside it.

import React, { Component } from 'react';
import {  View, Text, StyleSheet} from 'react-native';
import PropTypes from 'prop-types';

const styles = StyleSheet.create({
    itemsList: {
        flex: 1,
        flexDirection: 'column',
        justifyContent: 'space-around',
    },
    itemtext: {
        fontSize: 24,
        fontWeight: 'bold',
        textAlign: 'center',
    }
});

export default class ItemComponent extends Component {

  static propTypes = {
      items: PropTypes.array.isRequired
  };

  render() {
    return (
      <View style={styles.itemsList}>
        {this.props.items.map((item, index) => {
            return (
                <View key={index}>
                    <Text style={styles.itemtext}>{item.name}</Text>
                </View>
            )
        })}
      </View>
    );
  }
}

This is how you can integrate Firebase in a React Native application. There is another way to use Firebase database store as an API instead of referring to it, you can directly add in the source code like we did in our application. In that case, you can use the command axios to fetch the data and save it on the Firebase store and handle errors properly since axios is a promise based utility.

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -