AppDividend
Latest Code Tutorials

React Native Firebase Example

6,124

Get real time updates directly on you device, subscribe now.

React Native Firebase Example is the today’s topic. Getting started with React Native and Firebase. I was first skeptical about Firebase, but after using it, it seems like the Firebase may be able to speed up widespread mobile and web app development. In a traditional mobile or web app progress when you’re building something other.

Also, you can check out the below course to learn React Native From Scratch.
React Native – The Practical Guide

React Native Firebase Example

Let us start our example by installing the React Native Project.

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 are facing Yellow warnings like isMounted(…) is deprecated in plain javascript react classes” error with this dependencies then add the following code inside 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 required directories.

In the root of the project, make the one directory called src.  In that directory, create three folders.

  1. screens
  2. components
  3. services

Screens folder contains the screens which we need to display to the User. In our case, we will create three screens.

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

Services folder contains network files. It 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 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>
    )
  }
}

Same do 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, same for ListItem.js file.

Related Posts
1 of 8
// 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 need to install React Navigation library to transition the app from one screen to another screen.

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 to another screen. 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 the screen 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 Firebase console.

Go to the https://firebase.google.com and login to your Google account and create a new project.

Now, in React Native, we fetch the database config as a web app, so go to your web app section and get the config object. We need to connect our app to the firebase.

Create a new folder, inside src folder, called config and in that, make a new file called db.js. 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 you need to copy the whole config from your firebase app.

Step 7: Create a form the add the data.

Write the following code inside 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 style 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 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
    });
}

Now, we need to import this services file into 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 addItem function and passed our textbox value to that function and also imported the AlertIOS component to display the alert box saying that our data has been successfully 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 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>
        )
    }
}

Okay, now we need to create ItemComponent.js file inside 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

This is not pretty much design but, I just wanted you to guys see how it can connect with Firebase and we can fetch the data and display that on the Screen. That is the main moto of this Tutorial.

That is it, I know there is lots of stuff we can fix this but, we will tackle one by one in the future tutorials.

So, React Native Firebase Example Tutorial is over. Thanks for taking.

9 Comments
  1. Bob says

    You missed the bit to display the screen selection in Home.js 🙂

    1. Leonardo says

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

      1. Leonardo says

        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 (

        );
        }
        }

        1. Tori says

          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.

          1. vinod kumar says

            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 ;

  2. Qwerty says

    I am beginner in react native firebase. This page is very helpful for me.

  3. ahmad says

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

    1. jin says

      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

  4. Luckyfella says

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

Leave A Reply

Your email address will not be published.

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