React Native Firebase Authentication – Login and User Registration Tutorial

React Native Android IOS App React Native firebase React Native Tutorial

We will learn how to develop Login and User Registration functionality using Firebase Authentication services in this React Native 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.

In our react native app, we'll also include a little form where a user can enter his information to register and gain access to the programme. In order to login and register users, we will next use react-native components to access the Firebase authentication APIs.

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)

Create React Native Project

Create React Native app using below command.

npx react-native init <project name>

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 and Installation

We are using the latest React navigation 6 for switching between the screens. To use this, we have to do some installation. So, let’s install that. 


For Navigation

npm install @react-navigation/native @react-navigation/native-stack
npm install react-native-screens react-native-safe-area-context
or
yarn add @react-navigation/native @react-navigation/native-stack
yarn add react-native-screens react-native-safe-area-context

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 i --save @react-native-firebase/app @react-native-firebase/auth
or
yarn add @react-native-firebase/app @react-native-firebase/auth


After install dependencies run this command for iOS:

npx pod-install

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 Home screens.

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

mkdir screens
touch screens/login.tsx
touch screens/singup.tsx
touch screens/home.tsx


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

import React from 'react';
import {DefaultTheme, NavigationContainer} from '@react-navigation/native';
import {createNativeStackNavigator} from '@react-navigation/native-stack';
import Login from './screens/login';
import Signup from './screens/signup';
import Home from './screens/home';

const Stack = createNativeStackNavigator();
let theme = {
  ...DefaultTheme,
  color: {
    ...DefaultTheme.colors,
    background: '#fff',
  },
};

export default function App() {
  return (
    <NavigationContainer theme={theme}>
      <Stack.Navigator screenOptions={{headerShown: false}}>
        <Stack.Screen name="Login" component={Login} />
        <Stack.Screen name="Signup" component={Signup} />
        <Stack.Screen name="Home" component={Home} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

Create a components folder in src folder and create app input.tsx file and add the following code:

AppInput.tsx

/* eslint-disable prettier/prettier */
import React, {useState} from 'react';
import {TextInput} from 'react-native';

function AppInput({updateInputval, name, value, secure}) {
    const [focused, setFocused] = useState<boolean>(false);

    const changeValue = (e:any) => {
        updateInputval(e, name);
    };
    return (
        <TextInput
            onFocus={() => setFocused(true)}
            onBlur={() => setFocused(true)}
            onChangeText={(e) => changeValue(e)}
            value={value}
            placeholderTextColor={'#626262'}
            placeholder={name.toUpperCase()}
            secureTextEntry={secure ? secure : false}
            style={[
                {
                    fontSize: 14,
                    padding: 20,
                    backgroundColor: "#f1f4ff",
                    borderRadius: 10,
                    marginVertical: 10,
                    borderColor: "#c2c2c2",
                    borderWidth: 3
                },
                focused && {
                    borderColor: "#f6880e",
                    borderWidth: 3,
                    shadowColor: "#fdcc2d",
                    shadowOffset: { width: 4, height: 10 },
                    shadowOpacity: 0.2,
                    shadowRadius: 10,
                }
            ]} />
    );
}

export default AppInput;

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.

Add the following code in the screens/signup.tsx file.

/* eslint-disable prettier/prettier */
import React, {useState} from 'react';
import {Alert, Image, SafeAreaView, Text, TouchableOpacity, View} from 'react-native';
import AppInput from '../components/appinput';
import auth from '@react-native-firebase/auth';

// eslint-disable-next-line @typescript-eslint/no-unused-vars
const Signup: React.FC<Props> = ({navigation: {navigate}}) => {
  const [values, setValues] = useState({name: '', email: '', password: ''});
  const updateInputval = (val, key) => {
    const value = {...values};
    value[key] = val;
    setValues({...value})
  };

  const singupSubmit = () =>{
        console.log("values", values)
        if(!values.email && !values.password && !values.name){
            Alert.alert("Enter a required fields.");
            return false;
        }

        auth().createUserWithEmailAndPassword(values.email, values.password).then((res:any)=>{
            res.user.updateProfile({
                displayName:values.name,
            })
            console.log("user Created Successfully!");
            setValues({name: '', email: '', password: ''});
            navigate("Login");
        }).catch((error:any) => console.log(error.message))
  }

  return (
    <SafeAreaView>
      <View style={{padding: 20}}>
        <View style={{alignItems: 'center'}}>
          <Image
            resizeMode="contain"
            source={require('../../assets/firebase.png')}
            style={{height: 200}}
          />
          <Text
            style={{
              fontSize: 30,
              color: '#f6880e',
              marginVertical: 10,
              fontWeight: 'bold',
            }}>
            Sign up Here
          </Text>
        </View>
        <View style={{marginVertical: 30}}>
          <AppInput name="name" value={values.name} updateInputval={updateInputval} secure={false} />
          <AppInput name="email"  value={values.email} updateInputval={updateInputval} secure={false}  />
          <AppInput name="password"  value={values.password} updateInputval={updateInputval} secure={true} />
        </View>

        <TouchableOpacity
          onPress={() => singupSubmit()}
          style={{
            padding: 20,
            marginVertical: 10,
            borderRadius: 10,
            backgroundColor: '#f6880e',
            shadowOffset: {width: 0, height: 10},
            shadowOpacity: 0.3,
            shadowRadius: 10,
          }}>
          <Text style={{color: '#fff', textAlign: 'center', fontSize: 20}}>
            Sign up
          </Text>
        </TouchableOpacity>

        <TouchableOpacity
          onPress={() => {
            navigate('Login');
          }}
          style={{padding: 20, marginVertical: 30}}>
          <Text style={{color: '#000', textAlign: 'center', fontSize: 20}}>
            Already have an account
          </Text>
        </TouchableOpacity>
      </View>
    </SafeAreaView>
  );
};

export default Signup;


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

The signupSubmit() 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.

/* eslint-disable prettier/prettier */
import React, { useState } from 'react';
import {Alert, Image, SafeAreaView, Text, TouchableOpacity, View} from 'react-native';
import AppInput from '../components/appinput';
import auth from '@react-native-firebase/auth';

// eslint-disable-next-line @typescript-eslint/no-unused-vars
const Login: React.FC<Props> = ({navigation: {navigate}}) => {
    const [values, setValues] = useState({email: '', password: ''});
    const updateInputval = (val:any, key:any) => {
      const value = {...values};
      value[key] = val;
      setValues({...value});
    };

    const loginSubmit = () =>{
        if(!values.email && !values.password){
            Alert.alert("Enter a required fields.");
            return false;
        }
        auth().signInWithEmailAndPassword(values.email, values.password).then((res:any)=>{
            console.log(res);
            setValues({email: '', password: ''});
            navigate("Home");
        }).catch((error)=>console.log(error.message))
    }
  return (
        <SafeAreaView>
            <View style={{padding: 20}}>
                <View style={{alignItems:'center'}}>
                    <Image resizeMode='contain' source={require('../../assets/firebase.png')} style={{height:220}} />
                    <Text style={{fontSize:30, color:'#f6880e', marginVertical:10, fontWeight:'bold'}}>Login Here</Text>
                </View>
                <View style={{marginVertical:30}}>
                    <AppInput name="email"  value={values.email} updateInputval={updateInputval} secure={false}  />
                    <AppInput name="password"  value={values.password} updateInputval={updateInputval} secure={true}  />
                </View>

                <TouchableOpacity onPress={()=>loginSubmit()} style={{padding:20, marginVertical: 10,borderRadius:10, backgroundColor: "#f6880e",shadowOffset:{width:0, height:10},shadowOpacity: 0.3, shadowRadius: 10, }}>
                    <Text style={{color:"#fff", textAlign:"center", fontSize:20}}>Sign in</Text>
                </TouchableOpacity>

                <TouchableOpacity onPress={()=>{ navigate("Signup")}} style={{padding:20, marginVertical:30}}>
                    <Text style={{color:"#000", textAlign:"center", fontSize:20}}>Create new account</Text>
                </TouchableOpacity>
            </View>
        </SafeAreaView>
    );
};

export default Login;

We declared the signInWithEmailAndPassword() method inside the loginSubmit() 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 home.tsx file.

/* eslint-disable prettier/prettier */
import auth from '@react-native-firebase/auth';
import React from 'react';
import {Text, TouchableOpacity, View} from 'react-native';

// eslint-disable-next-line @typescript-eslint/no-unused-vars
const Home: React.FC<Props> = ({navigation: {navigate}}) => {
    const user:any = auth().currentUser?auth().currentUser:{};
    console.log("user", user)
    const signout = () =>{
        auth().signOut().then(()=>{
            navigate("Login")
        }).catch(err=>console.log(err.message));
    }
  return (
        // <SafeAreaView>
            <View style={{flex:1, display:'flex', justifyContent:'center', alignItems:'center', padding:30}}>
                <Text style={{fontSize:20, color:"#000", marginBottom:20}}>
                    Hello, {user?.displayName}
                </Text>
                <Text style={{fontSize:20, color:"#000", marginBottom:20}}>
                    {user?.email}
                </Text>
              
                <TouchableOpacity onPress={()=>signout()} style={{padding:20, marginVertical: 10,borderRadius:10, backgroundColor: "#f6880e",shadowOffset:{width:0, height:10},shadowOpacity: 0.3, shadowRadius: 10, width:"100%"}}>
                    <Text style={{color:"#fff", textAlign:"center", fontSize:20}}>Sign Out</Text>
                </TouchableOpacity>
            </View>
        // </SafeAreaView>
    );
};

export default Home;

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!

OutPut



React Native Android IOS App React Native firebase React Native Tutorial
Comments

AdBlock Detected!

Our website is made possible by displaying ads to our visitors. Please supporting us by whitelisting our website.