React Native Firebase – Login and User Registration Tutorial

Last Updated on by in React Native
In this React Native tutorial, we are going to learn how to create Login and User Registration functionalities using Firebase Authentication services.React Native Firebase - Login and User Registration Tutorial

We will start by setting up a react native app from scratch, create a new Firebase project, implement Firebase in a react native app.

We will also create a small form in our react native app where a user can submit his credentials to register and get access into the application. Next, we will access the Firebase authentication APIs from react-native components to login and register users.

Prerequisite

You should have Node & NPM set up on our device. We must be familiar with the following tools, frameworks, and packages to get started with this tutorial.

  • NPM
  • Node
  • IDE
  • Xcode
  • Firebase
  • Android Studio
  • React Native
  • React Native CLI
  • React Native Firebase Package
  • Terminal (macOS, Linux and Windows)

Install React Native Project

First, install create-react-native-app tool on your system.

sudo npm i -g create-react-native-app

Install React Native app using below command.

create-react-native-app rnFirebaseAuth

Select Y to install expo tool and run command to get inside the project folder.

cd rnFirebaseAuth

Firebase Account Setup

Visit console.firebase.google.com to create a Firebase project.

Setting up Firebase Project

Create Firebase account from Firebase dashboard. Click on “Create a project” button and create a brand new Firebase authentication project.

React Native Firebase Authentication Project

Enter project name and click on the “Continue” button.

Add Firebase App

Next, add Firebase to app, click on any of the icon based on your platform choice.

Register App

Enter the app’s nickname and click on the Next button.

Firebase configuration

We need these firebase configuration details to make the connection between react native and Firebase database.

Configure Firebase Sign-in Providers

As you can see at the left side in the Firebase dashboard a full list of Firebase features. Click on “Authentication” the users tab will contain the user’s list, and we will register the users via react native’s front-end.

configure Firebase Sign-in providers

Enable the sign-in methods, Email and Password and Login with Google.

Set up Firebase in React Native

We need to set up and configure Firebase in our react native application using a third party Firebase package.

Run the following command to install the Firebase package.

npm install firebase --save

Next, run the following command to create a database folder and firebase.js file.

mkdir database

touch database/firebase.js
// database/firebaseDb.js

import * as firebase from 'firebase';

const firebaseConfig = {
    apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    authDomain: "reactnativefirebase-00000.firebaseapp.com",
    databaseURL: "https://reactnativefirebase-00000.firebaseio.com",
    projectId: "reactnativefirebase-00000",
    storageBucket: "reactnativefirebase-00000.appspot.com",
    messagingSenderId: "000000000000000",
    appId: "1:000000000000000:web:000000000000000"
};

firebase.initializeApp(firebaseConfig);

export default firebase;

Now, we have successfully configured Firebase in react native app. We are now able to access the Firebase authentication services via its APIs.

Initiate Navigation in React Native

In this step we will configure routes in our react native app. In order to enable navigation, we need to create Login, Singup and Dashboard screens.

We are all set with the basic react native project, now we have to create the three screens.

mkdir components

touch components/signup.js
touch components/login.js
touch components/dashboard.js

Next, add the following code in the App.js file.

// App.js

import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

import Login from './components/login';
import Signup from './components/signup';
import Dashboard from './components/dashboard';

const Stack = createStackNavigator();

function MyStack() {
  return (
    <Stack.Navigator
      initialRouteName="Signup"
      screenOptions={{
        headerTitleAlign: 'center',
        headerStyle: {
          backgroundColor: '#3740FE',
        },
        headerTintColor: '#fff',
        headerTitleStyle: {
          fontWeight: 'bold',
        },
      }}>
      <Stack.Screen 
        name="Signup" 
        component={Signup} 
        options={{ title: 'Signup' }}
      />       
      <Stack.Screen 
        name="Login" 
        component={Login} 
        options={
          {title: 'Login'},
          {headerLeft: null} 
        }
      />
      <Stack.Screen 
       name="Dashboard" 
       component={Dashboard} 
       options={
         { title: 'Dashboard' },
         {headerLeft: null} 
       }
      />
    </Stack.Navigator>
  );
}

export default function App() {
  return (
    <NavigationContainer>
      <MyStack />
    </NavigationContainer>
  );
}

We have configured react native navigation using StackNavigator, we have also implemented the Header bar.

Register with Email and Password

In this step, we will learn how to implement Firebase User Authentication. We will create a basic form in our react native app, and It will have a user name, email and password values.

Registration Authentication with Email and Password

Add the following code in the components/signup.js file.

// components/signup.js

import React, { Component } from 'react';
import { StyleSheet, Text, View, TextInput, Button, Alert, ActivityIndicator } from 'react-native';
import firebase from '../database/firebase';


export default class Signup extends Component {
  
  constructor() {
    super();
    this.state = { 
      displayName: '',
      email: '', 
      password: '',
      isLoading: false
    }
  }

  updateInputVal = (val, prop) => {
    const state = this.state;
    state[prop] = val;
    this.setState(state);
  }

  registerUser = () => {
    if(this.state.email === '' && this.state.password === '') {
      Alert.alert('Enter details to signup!')
    } else {
      this.setState({
        isLoading: true,
      })
      firebase
      .auth()
      .createUserWithEmailAndPassword(this.state.email, this.state.password)
      .then((res) => {
        res.user.updateProfile({
          displayName: this.state.displayName
        })
        console.log('User registered successfully!')
        this.setState({
          isLoading: false,
          displayName: '',
          email: '', 
          password: ''
        })
        this.props.navigation.navigate('Login')
      })
      .catch(error => this.setState({ errorMessage: error.message }))      
    }
  }

  render() {
    if(this.state.isLoading){
      return(
        <View style={styles.preloader}>
          <ActivityIndicator size="large" color="#9E9E9E"/>
        </View>
      )
    }    
    return (
      <View style={styles.container}>  
        <TextInput
          style={styles.inputStyle}
          placeholder="Name"
          value={this.state.displayName}
          onChangeText={(val) => this.updateInputVal(val, 'displayName')}
        />      
        <TextInput
          style={styles.inputStyle}
          placeholder="Email"
          value={this.state.email}
          onChangeText={(val) => this.updateInputVal(val, 'email')}
        />
        <TextInput
          style={styles.inputStyle}
          placeholder="Password"
          value={this.state.password}
          onChangeText={(val) => this.updateInputVal(val, 'password')}
          maxLength={15}
          secureTextEntry={true}
        />   
        <Button
          color="#3740FE"
          title="Signup"
          onPress={() => this.registerUser()}
        />

        <Text 
          style={styles.loginText}
          onPress={() => this.props.navigation.navigate('Login')}>
          Already Registered? Click here to login
        </Text>                          
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    display: "flex",
    flexDirection: "column",
    justifyContent: "center",
    padding: 35,
    backgroundColor: '#fff'
  },
  inputStyle: {
    width: '100%',
    marginBottom: 15,
    paddingBottom: 15,
    alignSelf: "center",
    borderColor: "#ccc",
    borderBottomWidth: 1
  },
  loginText: {
    color: '#3740FE',
    marginTop: 25,
    textAlign: 'center'
  },
  preloader: {
    left: 0,
    right: 0,
    top: 0,
    bottom: 0,
    position: 'absolute',
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#fff'
  }
});

Creating a form is very simple in react native; we created a form for both iOS and Android using react native UI components.

The registerUser() method is handling the user registration; we are signing up using createUserWithEmailAndPassword(email, password) method via Firebase API.

The updateInputVal() function is being called when the user starts typing in the input field and updates the user registration form values.

Login User with email and password

Firebase comes with custom email and password auth as well as OAuth2 integrations for Facebook, Google, Twitter, GitHub and many more.

Firebase authentication allows users to read and writes the data in cloud storage and real-time database very quickly.

In the previous step, we learned how to sign up a new user using email/password and how to update the display name in the Firebase user object. Now, we need to log in the system by authenticating the email and password registered by the user.

Add the given below code in the login.js file.

// components/login.js

import React, { Component } from 'react';
import { StyleSheet, Text, View, TextInput, Button, Alert, ActivityIndicator } from 'react-native';
import firebase from '../database/firebase';


export default class Login extends Component {
  
  constructor() {
    super();
    this.state = { 
      email: '', 
      password: '',
      isLoading: false
    }
  }

  updateInputVal = (val, prop) => {
    const state = this.state;
    state[prop] = val;
    this.setState(state);
  }

  userLogin = () => {
    if(this.state.email === '' && this.state.password === '') {
      Alert.alert('Enter details to signin!')
    } else {
      this.setState({
        isLoading: true,
      })
      firebase
      .auth()
      .signInWithEmailAndPassword(this.state.email, this.state.password)
      .then((res) => {
        console.log(res)
        console.log('User logged-in successfully!')
        this.setState({
          isLoading: false,
          email: '', 
          password: ''
        })
        this.props.navigation.navigate('Dashboard')
      })
      .catch(error => this.setState({ errorMessage: error.message }))
    }
  }

  render() {
    if(this.state.isLoading){
      return(
        <View style={styles.preloader}>
          <ActivityIndicator size="large" color="#9E9E9E"/>
        </View>
      )
    }    
    return (
      <View style={styles.container}>  
        <TextInput
          style={styles.inputStyle}
          placeholder="Email"
          value={this.state.email}
          onChangeText={(val) => this.updateInputVal(val, 'email')}
        />
        <TextInput
          style={styles.inputStyle}
          placeholder="Password"
          value={this.state.password}
          onChangeText={(val) => this.updateInputVal(val, 'password')}
          maxLength={15}
          secureTextEntry={true}
        />   
        <Button
          color="#3740FE"
          title="Signin"
          onPress={() => this.userLogin()}
        />   

        <Text 
          style={styles.loginText}
          onPress={() => this.props.navigation.navigate('Signup')}>
          Don't have account? Click here to signup
        </Text>                          
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    display: "flex",
    flexDirection: "column",
    justifyContent: "center",
    padding: 35,
    backgroundColor: '#fff'
  },
  inputStyle: {
    width: '100%',
    marginBottom: 15,
    paddingBottom: 15,
    alignSelf: "center",
    borderColor: "#ccc",
    borderBottomWidth: 1
  },
  loginText: {
    color: '#3740FE',
    marginTop: 25,
    textAlign: 'center'
  },
  preloader: {
    left: 0,
    right: 0,
    top: 0,
    bottom: 0,
    position: 'absolute',
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#fff'
  }
});

We declared the signInWithEmailAndPassword() method inside the userLogin() function. We bind it to Signin button with onPress() event, user will be logged in the app when clicked on the Signin button.

Logout from Firebase via React Native

Now, we will check out how to log out from the Firebase, we need to call the signOut() method. Let’s see how it is implemented in a React Native app.

Add the following code in the dashboard.js file.

// components/dashboard.js

import React, { Component } from 'react';
import { StyleSheet, View, Text, Button } from 'react-native';
import firebase from '../database/firebase';

export default class Dashboard extends Component {
  constructor() {
    super();
    this.state = { 
      uid: ''
    }
  }

  signOut = () => {
    firebase.auth().signOut().then(() => {
      this.props.navigation.navigate('Login')
    })
    .catch(error => this.setState({ errorMessage: error.message }))
  }  

  render() {
    this.state = { 
      displayName: firebase.auth().currentUser.displayName,
      uid: firebase.auth().currentUser.uid
    }    
    return (
      <View style={styles.container}>
        <Text style = {styles.textStyle}>
          Hello, {this.state.displayName}
        </Text>

        <Button
          color="#3740FE"
          title="Logout"
          onPress={() => this.signOut()}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    display: "flex",
    justifyContent: 'center',
    alignItems: 'center',
    padding: 35,
    backgroundColor: '#fff'
  },
  textStyle: {
    fontSize: 15,
    marginBottom: 20
  }
});

React Native Firebase Logout

We access the firebase.auth().signOut() method to logout from the app, on the successful logout we are redirecting the user to the login screen.

Conclusion

We have completed React Native Firebase Authentication tutorial. In this tutorial, we learned how to Register a User and Login using email and password. We got a chance to learn how to implement Firebase in react native app in simple ways.

This is just a basic tutorial for beginners, especially for those who are just getting started with React Native and Firebase. I hope you will like this tutorial. Thanks for reading and Happy Coding!

You can download the full code of this tutorial from this GitHub repository.