React native email authentication with Firebase

Overview

In this shot, we’ll learn to integrate email authentication in React Native.

Installation

Create a new React Native application from the terminal:

npx react-native init authtutorial
cd authtutorial

Go to the firebase dashboard and create an android and iOS application named com.authtutorial ( or your application’s name).

We get two files called googleservices.json for android and googleServices-Info.plist for iOS. We need these two files for integrating firebase services in our React Native application.

Now enable email authentication in the Firebase dashboard.

Installation for android

Place the googleservices.json inside the android > app folder. Follow the below steps to initialize the Firebase in the android version of the application.

  1. Add the code below in build.gradle.
classpath 'com.google.gms:google-services:4.3.10'

  1. Add the code below in build.gradle in the app folder.
apply plugin: 'com.google.gms.google-services'

  1. Add build.gradle file at the top of the application.

  2. Add the code below in dependencies in same file.

dependencies {
  // Import the Firebase BoM
  implementation platform('com.google.firebase:firebase-bom:29.0.3')

Let’s move on to the configuration for the iOS version of the application.

Installation for iOS

Download the googleServices-Info.plist from the firebase dashboard and drag and drop it into Xcode.

Follow the below steps for Firebase configuration with iOS version of your application:

  1. Go to AppDelegate.m and add the code to initialize firebase in your iOS application.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// include the below Code
  if ([FIRApp defaultApp] == nil) {
      [FIRApp configure];
    }

  1. Add #import <Firebase.h> at the top of the file.

Android

Install the required npm packages from the terminal:

npm install --save @react-native-firebase/app @react-native-firebase/auth 

Now in App.js add the below code to integrate the email login to the application.

import React, {useState, useEffect} from 'react';
import {
SafeAreaView,
Text,
TextInput,
TouchableOpacity,
View,
} from 'react-native';
import auth from '@react-native-firebase/auth';
const App = () => {
const [user, setUser] = useState(null);
const [email, setEmail] = useState(null);
const [password, setPassword] = useState(null);
const [isSignUp, setIsSignUp] = useState(false);
const onAuthStateChanged = async userAuth => {
if (!userAuth) {
return;
}
if (userAuth) {
console.log(userAuth);
setUser(userAuth);
}
return () => userReference();
};
useEffect(() => {
const subscriber = auth().onAuthStateChanged(onAuthStateChanged);
return () => {
subscriber;
};
}, []);
const signUp = () => {
auth()
.createUserWithEmailAndPassword(email, password)
.then(() => {
alert('User account created & signed in!');
})
.catch(error => {
if (error.code === 'auth/email-already-in-use') {
alert('That email address is already in use!');
}
if (error.code === 'auth/invalid-email') {
alert('That email address is invalid!');
}
console.error(error);
});
};
const signIn = () => {
auth()
.signInWithEmailAndPassword(email, password)
.then(() => {
alert('User Signed In');
})
.catch(error => {
console.error(error);
});
};
const signOut = async () => {
auth().signOut();
setUser(null);
return () => userReference();
};
return (
<SafeAreaView style={{alignItems: 'center', flex: 1, marginTop: 100}}>
<View style={{margin: 10}}>
<Text>Email Sign In Tutorial</Text>
</View>
<View style={{margin: 10}}>
{user === null && (
<>
<TextInput
value={email}
onChangeText={e => setEmail(e)}
placeholder="Email"
style={{
borderWidth: 1,
margin: 10,
padding: 10,
}}></TextInput>
<TextInput
value={password}
onChangeText={e => setPassword(e)}
placeholder="password"
style={{borderWidth: 1, margin: 10, padding: 10}}></TextInput>
{isSignUp ? (
<>
<TouchableOpacity
style={{
borderWidth: 1,
margin: 10,
padding: 10,
alignItems: 'center',
}}
onPress={() => signUp()}>
<Text>Sign up</Text>
</TouchableOpacity>
<Text onPress={() => setIsSignUp(false)}>
Already have an account? Sign In
</Text>
</>
) : (
<>
<TouchableOpacity
style={{
borderWidth: 1,
margin: 10,
padding: 10,
alignItems: 'center',
}}
onPress={() => signIn()}>
<Text>Sign in</Text>
</TouchableOpacity>
<Text onPress={() => setIsSignUp(true)}>
Already have an account? Sign In
</Text>
</>
)}
</>
)}
</View>
{user !== null && (
<View style={{margin: 10}}>
<Text style={{margin: 10}}>{user.email}</Text>
<TouchableOpacity onPress={signOut} style={{alignItems: 'center'}}>
<Text>Sign Out</Text>
</TouchableOpacity>
</View>
)}
</SafeAreaView>
);
};
export default App;

Explanation

In the code snippet above:

  • We ask the user to sign up with their email and password. Once the user has signed up Firebase automatically authenticates the user.

  • If the user has already signed up, we use the sign-in method from Firebase auth to sign in the user. If the user is authenticated, then we give a button to let them sign out.

  • We also create a function that listens to the authChanges.

  • We create two input fields called Email and Password and listen to the user’s inputs.

iOS

In the terminal, run the command to install pods in your project:

cd ios 
pod install

The code is the same as in App.js for iOS.

Conclusion

In this article, we learned to integrate email authentication with our react native application.

Free Resources