Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

firebase
communitycreator

How to set up Firebase in a React Native project

krissanawat

We are going to use a popular react-native-firebase package, version 6 from invertase. We will follow the minimalist principle by separating standalone package into multiple packages that require the core package. First, we will install the package and choose only the required features.

Then, we come back to the React Native project that we created earlier and open an integrated terminal to install the core Firebase package with:

yarn add @react-native-firebase/app

Next, install two feature packages for authentication and Firestore. For that, we need to run the following command:

yarn add @react-native-firebase/auth @react-native-firestore

Lastly, we will install cocoa pod using the following command:

cd ios ; pod install

In this tutorial, we will configure and develop the iOS platform only. Feel free to check out the official documentation for Android implementation.

Now, we need to try to run the command below:

react-native run-ios

Then, at the firebase console, the following message will be displayed if Firebase has been successfully integrated to the project:

Installing and setting up React Navigation

Now, we will setup react-navigation to helps us navigate to another screen. Just like react-native-firebase, we will follow the minimalist principles in this setup as well. Therefore, we will selectively install the required packages.

First, we need to install the main package using:

yarn add @react-navigation/native

Then, install other the dependencies:

yarn add react-native-gesture-handler react-native-reanimated react-native-screens react-native-safe-area-context @react-native-community/masked-view

Linking is automatic in React Native 0.60 and higher; so, you don’t need to run the react-native link.

If you’re on a Mac and developing for iOS, you need to install the pods (via Cocoapods) to complete the linking:

cd ios ; pod install

To finalize the installation of the react-native-gesture-handler, we need to add the following code at the top (make sure that it’s at the top and there’s nothing else before it) of your entry file, such as index.js or App.js:

import 'react-native-gesture-handler';

Note: If you skip this step, your app may crash in production, even if it works fine in development.

Now, we need to wrap the whole app in NavigationContainer. Usually, you’d do this in your entry file, such as index.js or App.js:

import { AppRegistry } from 'react-native';
import App from './App';
import { name as appName } from './app.json';
import 'react-native-gesture-handler';
import { NavigationContainer } from '@react-navigation/native'
AppRegistry.registerComponent(appName, () =>
    <NavigationContainer>
        <App />
    </NavigationContainer>
);

In this tutorial, we only want basic screen navigation. So, we will only install the stack navigator. Do this using the following command:

yarn add @react-navigation/stack

Now, in App.js, we need to import the package and create a new instance, as shown below:

import { createStackNavigator } from '@react-navigation/stack'
const Stack = createStackNavigator();

Then, we need to create new files for screens that we want to use, such as Register, Login, and Home screen:

Next, we need to import the screens to App.js as shown below:

import LoginScreen from './screens/LoginScreen/index'
import HomeScreen from './screens/HomeScreen'
import RegistrationScreen from './screens/RegistrationScreen'

Then, wrap all three screens with Stack navigator, as shown below:

return (
    <Stack.Navigator>
            <Stack.Screen name="Home" component={HomeScreen} />
            <Stack.Screen name="Login" component={LoginScreen} />
            <Stack.Screen name="Registration" component={RegistrationScreen} />
    </Stack.Navigator>
  );

The react-navigation configuration is now complete. Let’s move forward onto the registration screen.

For the registration screen, we will import the following packages:

import React, { useState } from 'react'
import { Image, Text, TextInput, TouchableOpacity, View } from 'react-native'
import styles from './styles';
import auth from '@react-native-firebase/auth'
import firestore from '@react-native-firebase/firestore'

We now need to create a functional component with four state variable. This is shown below:

const [fullName, setFullName] = useState('')
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [confirmPassword, setConfirmPassword] = useState('')

Then, we will create a simple form and use the state to handle the form value when changes occur. This is shown below:

return (
        <View >
            <Image
                style={styles.logo}
                source={require('./../../assets/icon.png')}
            />
            <TextInput
                style={styles.input}
                placeholder='Full Name'
                placeholderTextColor="#aaaaaa"
                onChangeText={(text) => setFullName(text)}
                value={fullName}
                underlineColorAndroid="transparent"
                autoCapitalize="none"
            />
            <TextInput
                style={styles.input}
                placeholder='E-mail'
                placeholderTextColor="#aaaaaa"
                onChangeText={(text) => setEmail(text)}
                value={email}
                underlineColorAndroid="transparent"
                autoCapitalize="none"
            />
            <TextInput
                style={styles.input}
                placeholderTextColor="#aaaaaa"
                secureTextEntry
                placeholder='Password'
                onChangeText={(text) => setPassword(text)}
                value={password}
                underlineColorAndroid="transparent"
                autoCapitalize="none"
            />
            <TextInput
                style={styles.input}
                placeholderTextColor="#aaaaaa"
                secureTextEntry
                placeholder='Confirm Password'
                onChangeText={(text) => setConfirmPassword(text)}
                value={confirmPassword}
                underlineColorAndroid="transparent"
                autoCapitalize="none"
            />
            <TouchableOpacity
                style={styles.button}
                onPress={() => onRegisterPress()}>
                <Text style={styles.buttonTitle}>Create account</Text>
            </TouchableOpacity>
            <View style={styles.footerView}>
                <Text style={styles.footerText}>Already got an account? <Text onPress={onFooterLinkPress} style={styles.footerLink}>Log in</Text></Text>
            </View>
        </View>
    )

Next, we need to create a function that will allow us to use a Firebase authentication package. Once registered, we need to store the user data on Firestore then navigate to Homescreen. The code for this is:

const onRegisterPress = () => {
        if (password !== confirmPassword) {
            alert("Passwords don't match.")
            return
        }
auth()
            .createUserWithEmailAndPassword(email, password)
            .then((response) => {
                const uid = response.user.uid
                const data = {
                    id: uid,
                    email,
                    fullName,
                };
                const usersRef = firestore().collection('users')
                usersRef
                    .doc(uid)
                    .set(data)
                    .then(() => {
                        navigation.navigate('Home', { user: data })
                    })
                    .catch((error) => {
                        alert(error)
                    });
            })
            .catch((error) => {
                alert(error)
            });
    }

Now, we can re-run the app in the emulator, but an error occurs. This error occurred because we did not active the login method in the firebase console. This error alert simulation is shown in the emulator screen below:

Now, in order to make it work, we need to open firebase console > Authentication > Sign-in Method and enable E-mail/Password, as shown below:

Our registration process will finally work as shown:

The user data will also be stored in the Firestore, as shown below:

After successful registration, we will be navigated to the home screen. But first, we need to implement the Home screen.

RELATED TAGS

firebase
communitycreator

CONTRIBUTOR

krissanawat
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring