How to Build a React Native App and Integrate It with Firebase

To work with Firebase with React Native, use the Firebase package. The Firebase package provides Firebase.initializeApp() function to initialize Firebase in React Native. It provides the ref() function, which we can chain and use the push() function to add elements to Firebase’s real-time database.

Here are the steps to build a React Native App and Integrate It with Firebase:

Step 1: Install React Native.

Install the React Native CLI using the following command.

# for mac users

sudo npm install -g react-native-cli

# for windows users: open cmd on admin mode and type 

npm install -g react-native-cli

Now, create our project using the following command.

react-native init RNFbase

Go into that project.

cd RNFbase

Start the package server and simulator using the following command.

react-native run-ios --simulator="iPhone X"

You will see this screen.

React Native Firebase Example

If you face Yellow warnings like isMounted(…) is deprecated in plain javascript react classes” error with these dependencies, add the following code inside the App.js file.

// App.js

import { YellowBox } from 'react-native';

YellowBox.ignoreWarnings(['Warning: isMounted(...) is deprecated', 'Module RCTImageLoader']);

Step 2: Install Firebase Dependency.

Type the following command to install the Firebase.

yarn add firebase

# or

npm install firebase --save

Step 3: Create the required directories.

In the project’s root, make one directory called src. n that directory, and create three folders.

  1. screens
  2. components
  3. services

The screens folder contains the screens we need to display to the User.  n our case, we will create three screens.

The components folder contains the mobile components we will use to display the data from the API.

The services folder contains network files.  t is the files in which we will write the code to make a request to the server and get the response from the server.

Step 4: Create two screens.

Inside the src >>  screens folder, create the following files.

  1.  Home.js
  2. AddItem.js
  3. ListItem.js

Home.js is the pure React Native class.

// 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>
    )
  }
}

The same goes for the AddItem.js file.

// 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>
    )
  }
}

Also, the same for the ListItem.js file.

// ListItem.js

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

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

Step 5: Integrate React Native Navigation.

We must install React Navigation library to transition the app from one screen to another.

yarn add react-navigation

# or

npm install react-navigation --save

Now, after installing, go to the App.js file. We will use StackNavigator to transit from one scr en to another. It is routing for our application.

// App.js

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

YellowBox.ignoreWarnings(['Warning: isMounted(...) is deprecated', 'Module RCTImageLoader']);

const AppNavigator = StackNavigator({
  HomeScreen: { screen: Home },
  AddItemScreen: { screen: AddItem },
  ListItemScreen: { screen: ListItem }
});

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

We have included both screens here and passed that screen into the StackNavigator function. It will handle the transition of our screens. HomeScreen displays like the following.

React Native Firebase Tutorial

Step 6: Create a database in the Firebase console.

Go to https://firebase.google.com, log in to your Google account, and create a new project.

In React Native, we fetch the database config as a web app, so go to your web app section and get the config object  Next, we need to connect our app to the Firebase.

Create a new folder inside the src folder called config, and make a new file called db.js. Then, write the following code in it.

// db.js

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

You have your configuration values, so copy the config from your Firebase app.

Step 7: Create a form, then add the data.

Write the following code inside the AddItem.js file.

// AddItem.js

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

export default class AddItem extends Component {
  constructor(props) {
      super(props);
      this.state = {
        name: '',
        error: false
      }
      this.handleChange = this.handleChange.bind(this);
      this.handleSubmit = this.handleSubmit.bind(this);
    }
    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: '#2a8ab7'
  },
  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'
  }
});

So, I have defined some basic styles of our form. So our AddItem.js screen looks like this.

Firebase React Native Example

Step 8: Create a service file to add data to Firebase.

Inside the services folder, create one file called ItemService.js.

// ItemService.js

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

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

We need to import this services file into the AddItem.js file.

// AddItem.js

import React, { Component } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TextInput,
  TouchableHighlight,
  AlertIOS
} from 'react-native';
import { addItem } from '../services/ItemService';

export default class AddItem extends Component {
  constructor(props) {
      super(props);
      this.state = {
        name: ''
      }
      this.handleChange = this.handleChange.bind(this);
      this.handleSubmit = this.handleSubmit.bind(this);
    }
    handleChange(e) {
      this.setState({
        name: e.nativeEvent.text
      });
    }
    handleSubmit() {
      addItem(this.state.name);
      AlertIOS.alert(
        'Item saved successfully'
       );
    }
  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: '#2a8ab7'
  },
  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'
  }
});

I have imported the addItem function and passed our textbox value to that function. I also imported the AlertIOS component to display the alert box saying our data was saved.

React Native Firebase save data

Also, you can see the data in the Firebase.

Firebase Tutorial

Step 9: Display Items.

Write the following code inside the ListItem.js file.

// ListItem.js

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

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

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

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

export default class ListItem 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 must create the ItemComponent.js file inside the src  >>  components folder. It will display our data from the Firebase.

// ItemComponent.js

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>
    );
  }
}

React Native Fetch Data

That’s it for this Tutorial. Thanks for taking it.

16 thoughts on “How to Build a React Native App and Integrate It with Firebase”

    • Yeah! I miss the part where we configure the Home Screen with the links/buttons to the other pages! The rest is great!

      Reply
      • This is how I got it to work!
        // App.js

        import React, { Component } from ‘react’;
        import {
        Platform,
        StyleSheet,
        Text,
        View
        } from ‘react-native’;
        import { StackNavigator } from ‘react-navigation’;
        import Home from ‘./src/screens/Home’;
        import AddItem from ‘./src/screens/AddItem’;
        import ListItem from ‘./src/screens/ListItem’;
        import { YellowBox } from ‘react-native’;

        const AppNavigator = StackNavigator({
        HomeScreen: { screen: Home },
        AddItemScreen: { screen: AddItem },
        ListItemScreen: { screen: ListItem }
        });

        export default class App extends Component {
        render() {
        return (

        );
        }
        }

        Reply
        • Hey, I am having the same issue. Posting your fix still gives me a syntax error. It wants to return something and doesn’t like the empty return. I’m new to react-native so I’m not sure how to fix.

          Reply
          • please try with this code no need of having return here.

            // App.js
            // create Home, AddItem, ListItem three components with three files,
            // and import them in this file by providing correct path.
            import { StackNavigator } from ‘react-navigation’;
            import Home from ‘./src/screens/Home’;
            import AddItem from ‘./src/screens/AddItem’;
            import ListItem from ‘./src/screens/ListItem’;

            const AppNavigator = StackNavigator({
            HomeScreen: { screen: Home },
            AddItemScreen: { screen: AddItem },
            ListItemScreen: { screen: ListItem }
            });

            export default AppNavigator ;

  1. Hi,i I am getting the following error message , “undefined is not an object ( evaluating ‘_db2.default.ref’)

    my database name is ‘myClientData’. is it right “db.ref(‘/myClientData’).push({
    name: “myname”
    });

    Reply
    • I had similar issue
      in mycase

      import db from ‘./src/DB.js’;
      i forgot the bracket around db and changed to

      import { db } from ‘./src/DB.js’;

      hope it helps

      Reply
  2. I’m glad having found your basic firebase tutorial – thanks a lot, it’s very helpful to get the basic understanding how it works!

    Reply
  3. You might get Objects are not valid as a React child (found: object with keys {$$typeof, type, key, ref, props, _owner, _store})… error while running the project, as of now there is some issue with firebase library, so just move to firebase version 5.0.3 for now.
    Use this command
    npm install firebase@5.0.3

    Reply
  4. thanks for this beautiful guidance…
    at step 5, add createAppContainer for grouping stack or else it will show an error

    this is my working code……

    import React, { Component } from ‘react’;
    // import {Platform, Text, View, YellowBox } from ‘react-native’;
    // import { YellowBox } from ‘react-native’;

    import {createStackNavigator, createAppContainer} from ‘react-navigation’;

    import Home from ‘./src/screens/Home’;
    import AddItem from ‘./src/screens/AddItem’;
    import ListItem from ‘./src/screens/ListItem’;

    // YellowBox.ignoreWarnings([‘Warning: isMounted(…) is deprecated’,’Module RCTImageLoader’]);

    const AppNavigator = createStackNavigator({
    HomeScreen :{screen : Home},
    AddItemScreen : {screen : AddItem},
    ListItemScreen : {screen : ListItem}
    });

    const AppContainer =createAppContainer(AppNavigator);

    export default class App extends Component {
    render() {
    return (

    );
    }
    }

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.