In this React Native step by step tutorial, we will show you an example of using Firebase email authentication or log in with React Native iOS and Android apps. The environment is very simple, just React Native mobile apps as a client and Firebase email authentication as a server. We will use the latest React Hooks and React Native Firebase library to develop this login app.
The scenario for this React Native Firebase Email tutorial is very simple. Just a login page/screen, register screen, reset password screen and home screen as a secure screen for the successful login landing page. The flow described in this diagram:
The following tools, frameworks, and libraries are required for this tutorial:
Before start to the main steps, make sure that you have installed Node.js and can run npm
in the terminal or command line. To check the existing or installed Node.js environment open the terminal/command line then type this command.
node -v
v8.12.0
npm -v
6.4.1
yarn -v
1.10.1
We have to go to the Google Firebase Console https://console.firebase.google.com/ to set up the Firebase email authentication. After login using your Gmail account, it will be redirected to the Firebase welcome page.
Click the “Create a Project” button then enter the project name (ours: “My React Native”).
Click the “Continue” button then disable the Google analytics for this project.
Click the “Create Project” button then click the “Continue” button after the new Project is ready. Now, you will be redirected to the dashboard of the new project.
Next, choose to Develop -> Authentication on the left pane.
Click on the “Sign-in Method” tab then click Email/Password.
Click the “Enable” switch then click the “Save” button. Now, you will see the “Email/Password” enabled. Next, click the “Gear” button on the left pane then click Project Settings.
To set up iOS Apps, scroll down the Settings pane then click the iOS icon button.
Fill the iOS bundle ID that registered in your Apple Developer account then click the “Register App” button. Click “Download GoogleService-Info.plist” button to download the configuration file for iOS app then click the “Next” button few times until the end of the wizard step.
Click the “Continue to console” button. To set up Android apps, scroll down then click the “Add app” button then click the “Android icon” button.
Click the “Register App” button then click the “Download google-service.json” button to download the Android Firebase configuration file. Click the “Next” button few times until the end of the wizard steps.
Click the “Continue to console” button. Now, the Google Firebase email authentication is ready to use.
We will use React Native CLI to create a new React Native app. To install it, type this command in your App projects folder.
sudo npm install -g react-native-cli
Then create a React Native App using this command from your project directory.
react-native init RNEmailAuth
Next, go to the newly created React App folder and run the React Native app to the iOS simulator.
cd RNEmailAuth && npx react-native run-ios
Or run to the Android device/emulator.
cd RNEmailAuth && npx react-native run-android
When a new terminal window opened, go to the React Native project folder then run the Metro bundler server.
cd ~/Apps/RNEmailAuth && yarn start
Now, you will see this in the iOS simulator.
Next, we will change the iOS and Android package name or bundle ID to match the Firebase configuration files. For iOS, open the ios/RNEmailAuth.xcworkspace
file using XCode.
Just change the Bundle Identifier (ours: com.djamware.rnemailauth) and it ready to use with the Firebase Authentication Email/Password.
For Android a little tricky, first, change the source folders which previously android/app/src/main/java/com/rnemailauth
become android/app/src/main/java/com/djamware/rnemailauth
.
Next, open and edit android/app/src/main/java/com/djamware/rnemailauth/MainActivity.java
and MainApplication.java
then replace this package name.
package com.rnemailauth;
to
package com.djamware.rnemailauth;
Next, open and edit android/app/src/main/AndroidManifest.xml
then change this line.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.rnemailauth">
To
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.djamware.rnemailauth">
Next, open edit android/app/build.gradle
then change the application ID to the new package.
android {
...
defaultConfig {
applicationId "com.djamware.rnemailauth"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1
versionName "1.0"
}
...
}
Next, open and edit android/app/BUCK
then change the android_build_config and android_resource package name.
android_build_config(
name = "build_config",
package = "com.djamware.rnemailauth",
)
android_resource(
name = "res",
package = "com.djamware.rnemailauth",
res = "src/main/res",
)
Finally, run this command from the android folder to clean up the Gradle.
./gradlew clean
To make integration easier, we use the RNFirebase Authentication module https://github.com/invertase/react-native-firebase/tree/master/packages/auth for accessing Firebase Authentication from the React Native apps. For that, type this command to install the module.
yarn add @react-native-firebase/app @react-native-firebase/auth
To make this React Native Firebase Authentication working on iOS devices, make sure you have XCode Signing Development Team. Otherwise, you only can run this iOS app on the simulator.
Next, open the ios/RNEmailAuth.xcworkspace
from the XCode then add the previously downloaded GoogleService-Info.plist to the XCode project name.
After added to the XCode project will be like this.
Next, open and edit ios/Podfile
then add this line of RNFBAuth.
target 'app' do
...
pod 'RNFBAuth', :path => '../node_modules/@react-native-firebase/auth'
end
Next, run the Pod installation with repo-update after going to the ios folder.
cd ios && pod install --repo-update
Next, open and edit RNEmailAuth/AppDelegate.m
then add these import of the Firebase.
#import <Firebase.h>
At the beginning of the **didFinishLaunchingWithOptions:(NSDictionary *)launchOptions**
method add this line to initialize Firebase.
[FIRApp configure];
Copy the previously downloaded google-services.json to android/app/
folder.
cp ~/Downloads/google-services.json android/app/
Next, open and edit android/build.gradle
then add this line inside the dependencies body.
dependencies {
...
classpath("com.google.gms:google-services:4.2.0")
}
Next, open and edit android/app/build.gradle
the add this line at the bottom of the file.
apply plugin: 'com.google.gms.google-services'
That it’s, all configuration was auto-linked when to add @react-native-firebase/app and @react-native-firebase/auth. If not auto-link, you can do a manual link like this.
react-native link @react-native-firebase/app
react-native link @react-native-firebase/auth
Before implementing the Firebase Authentication email password login, we need to add pages for login, register, and home. For that, start your IDE to create those files. If you are using Visual Studio Code, type this command in the terminal at the root of this project folder.
code .
Create a folder for those files first then create files for login, register, and home.
mkdir components
touch components/Login.js
touch components/Register.js
touch components/Home.js
touch components/Reset.js
Open and edit components/Login.js
then add these lines of React Hooks codes and disable Navigation header.
import React, { useState, useEffect } from 'react';
import { Button, View, Text } from 'react-native';
export default function Login({ navigation }) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Login</Text>
</View>
);
}
Login.navigationOptions = ({ navigation }) => ({
title: 'Login',
headerShown: false,
});
Open and edit components/Register.js
then add these lines of React Hooks codes and disable Navigation header.
import React, { useState, useEffect } from 'react';
import { Button, View, Text } from 'react-native';
export default function Register({ navigation }) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Register</Text>
</View>
);
}
Register.navigationOptions = ({ navigation }) => ({
title: 'Register',
headerShown: false,
});
Open and edit components/Home.js
then add these lines of React Hooks codes.
import React, { useState, useEffect } from 'react';
import { Button, View, Text } from 'react-native';
export default function Home({ navigation }) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home</Text>
</View>
);
}
Home.navigationOptions = ({ navigation }) => ({
title: 'Home',
});
Open and edit components/Reset.js
then add these lines of React Hooks codes and disable Navigation header.
import React, { useState, useEffect } from 'react';
import { Button, View, Text } from 'react-native';
export default function Reset({ navigation }) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Reset</Text>
</View>
);
}
Reset.navigationOptions = ({ navigation }) => ({
title: 'Reset',
headerShown: false,
});
Next, we will add the Navigation header in the screen layout for this Mobile Apps. For that, add the libraries of React Navigation and React Native Gesture Handler by type these commands.
yarn add react-navigation react-navigation-stack react-native-safe-area-context @react-native-community/masked-view react-native-gesture-handler
For iOS, go to the ios folder then install Pod.
cd ios && pod install
Next, we will implement stack navigation in the current App.js. Open and edit App.js
then add these imports of react-navigation createAppContainer, react-navigation-stack createStackNavigator, log in, Register, and Home.
import { createAppContainer } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';
import Login from './components/Login';
import Register from './components/Register';
import Home from './components/Home';
import Reset from './components/Reset';
Add a constant variable after the imports that initialize createStackNavigator.
const RootStack = createStackNavigator(
{
Login: Login,
Register: Register,
Home: Home,
Reset: Reset,
},
{
initialRouteName: 'Home',
defaultNavigationOptions: {
headerStyle: {
backgroundColor: '#19AC52',
},
headerTintColor: '#fff',
headerTitleStyle: {
fontWeight: 'bold',
},
},
},
);
Add the above createStackNavigator to the createAppContainer.
const RootContainer = createAppContainer(RootStack);
Replace the current main function and the export with this export function.
export default function App() {
return (
<RootContainer />
)
}
The login screen will contain Email, Password Input Text, login, Register, and Reset Password Button. The action of the Login button will log in the entered email and password to Firebase authentication. Register and Reset button will redirect to Register and Reset screen.
We will use additional elements to build the login, register and reset forms. For that, type this command to install the react-native-elements and react-native-vector-icons modules.
yarn add react-native-elements react-native-vector-icons
To make the react-native-vector-icons working on iOS, open and edit ios/RNEmailAuth/Info.plist
then add these lines of UIAppFonts before the end of .
<dict>
...
<key>UIAppFonts</key>
<array>
<string>AntDesign.ttf</string>
<string>Entypo.ttf</string>
<string>EvilIcons.ttf</string>
<string>Feather.ttf</string>
<string>FontAwesome.ttf</string>
<string>FontAwesome5_Brands.ttf</string>
<string>FontAwesome5_Regular.ttf</string>
<string>FontAwesome5_Solid.ttf</string>
<string>Foundation.ttf</string>
<string>Ionicons.ttf</string>
<string>MaterialIcons.ttf</string>
<string>MaterialCommunityIcons.ttf</string>
<string>SimpleLineIcons.ttf</string>
<string>Octicons.ttf</string>
<string>Zocial.ttf</string>
</array>
</dict>
Next, open and edit components/Login.js
then add/replace these imports of the required elements and Firebase auth.
import React, { useState } from 'react';
import { StyleSheet, ActivityIndicator, View, Text, Alert } from 'react-native';
import { Button, Input, Icon } from 'react-native-elements';
import auth from '@react-native-firebase/auth';
Add the required useState constant variable at the first line of the Login function body.
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [showLoading, setShowLoading] = useState(false);
Add a function of Firebase login with email and password after those constants.
const login = async() => {
setShowLoading(true);
try {
const doLogin = await auth().signInWithEmailAndPassword(email, password);
setShowLoading(false);
if(doLogin.user) {
navigation.navigate('Home');
}
} catch (e) {
setShowLoading(false);
Alert.alert(
e.message
);
}
};
Modify these views after the login function to implementing the Login Form UI.
return (
<View style={styles.container}>
<View style={styles.formContainer}>
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center'}}>
<Text style={{ fontSize: 28, height: 50 }}>Please Login!</Text>
</View>
<View style={styles.subContainer}>
<Input
style={styles.textInput}
placeholder='Your Email'
leftIcon={
<Icon
name='mail'
size={24}
/>
}
value={email}
onChangeText={setEmail}
/>
</View>
<View style={styles.subContainer}>
<Input
style={styles.textInput}
placeholder='Your Password'
leftIcon={
<Icon
name='lock'
size={24}
/>
}
secureTextEntry={true}
value={password}
onChangeText={setPassword}
/>
</View>
<View style={styles.subContainer}>
<Button
style={styles.textInput}
icon={
<Icon
name="input"
size={15}
color="white"
/>
}
title="Login"
onPress={() => login()} />
</View>
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Forgot Password?</Text>
</View>
<View style={styles.subContainer}>
<Button
style={styles.textInput}
icon={
<Icon
name="refresh"
size={15}
color="white"
/>
}
title="Reset Password"
onPress={() => {
navigation.navigate('Reset');
}} />
</View>
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Not a user?</Text>
</View>
<View style={styles.subContainer}>
<Button
style={styles.textInput}
icon={
<Icon
name="check-circle"
size={15}
color="white"
/>
}
title="Register"
onPress={() => {
navigation.navigate('Register');
}} />
</View>
{showLoading &&
<View style={styles.activity}>
<ActivityIndicator size="large" color="#0000ff" />
</View>
}
</View>
</View>
);
Finally, add these lines of styles after the navigationOptions.
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
formContainer: {
height: 400,
padding: 20
},
subContainer: {
marginBottom: 20,
padding: 5,
},
activity: {
position: 'absolute',
left: 0,
right: 0,
top: 0,
bottom: 0,
alignItems: 'center',
justifyContent: 'center'
},
textInput: {
fontSize: 18,
margin: 5,
width: 200
},
})
The Firebase authentication email password register or sign-in almost the same with the previous Login. The difference just a Firebase method, this time using createUserWithEmailAndPassword. Open and edit components/Register.js
then add these imports to the required elements and Firebase auth.
import React, { useState } from 'react';
import { StyleSheet, ActivityIndicator, View, Text, Alert } from 'react-native';
import { Button, Input, Icon } from 'react-native-elements';
import auth from '@react-native-firebase/auth';
Add these useState constant variables at the first line of the Register function body.
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [showLoading, setShowLoading] = useState(false);
Add the asynchronous function to register to the Firebase auth with email and password.
const register = async() => {
setShowLoading(true);
try {
const doRegister = await auth().createUserWithEmailAndPassword(email, password);
setShowLoading(false);
if(doRegister.user) {
navigation.navigate('Home');
}
} catch (e) {
setShowLoading(false);
Alert.alert(
e.message
);
}
};
Modify the views that implement the Register Form using a combination of react-native and react-native-elements elements.
return (
<View style={styles.container}>
<View style={styles.formContainer}>
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text style={{ fontSize: 28, height: 50 }}>Register Here!</Text>
</View>
<View style={styles.subContainer}>
<Input
style={styles.textInput}
placeholder='Your Email'
leftIcon={
<Icon
name='mail'
size={24}
/>
}
value={email}
onChangeText={setEmail}
/>
</View>
<View style={styles.subContainer}>
<Input
style={styles.textInput}
placeholder='Your Password'
leftIcon={
<Icon
name='lock'
size={24}
/>
}
secureTextEntry={true}
value={password}
onChangeText={setPassword}
/>
</View>
<View style={styles.subContainer}>
<Button
style={styles.textInput}
icon={
<Icon
name="check-circle"
size={15}
color="white"
/>
}
title="Register"
onPress={() => register()} />
</View>
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Already a user?</Text>
</View>
<View style={styles.subContainer}>
<Button
style={styles.textInput}
icon={
<Icon
name="input"
size={15}
color="white"
/>
}
title="Login"
onPress={() => {
navigation.navigate('Login');
}} />
</View>
{showLoading &&
<View style={styles.activity}>
<ActivityIndicator size="large" color="#0000ff" />
</View>
}
</View>
</View>
);
Finally, add these codes of styles after the navigationOptions.
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
formContainer: {
height: 400,
padding: 20
},
subContainer: {
marginBottom: 20,
padding: 5,
},
activity: {
position: 'absolute',
left: 0,
right: 0,
top: 0,
bottom: 0,
alignItems: 'center',
justifyContent: 'center'
},
textInput: {
fontSize: 18,
margin: 5,
width: 200
},
})
The reset password screen just required one email input text and reset button. Also, a button to navigate back the previous screen. Open and edit components/Reset.js
then add/replace these imports of the required elements and Firebase auth.
import React, { useState } from 'react';
import { StyleSheet, ActivityIndicator, View, Text, Alert } from 'react-native';
import { Button, Input, Icon } from 'react-native-elements';
import auth from '@react-native-firebase/auth';
Add these required useState constant variables at the first line of the Reset function body.
const [email, setEmail] = useState('');
const [showLoading, setShowLoading] = useState(false);
Add this function to send an email for a reset password to Firebase authentication. The Firebase will send the reset link email to the email that sends in this function.
const reset = async() => {
setShowLoading(true);
try {
await auth().sendPasswordResetEmail(email);
setShowLoading(false);
} catch (e) {
setShowLoading(false);
Alert.alert(
e.message
);
}
};
Add this implementation of view for Reset password form by modifying the existing return.
return (
<View style={styles.container}>
<View style={styles.formContainer}>
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center'}}>
<Text style={{ fontSize: 28, height: 50 }}>Reset Password!</Text>
</View>
<View style={styles.subContainer}>
<Input
style={styles.textInput}
placeholder='Your Email'
leftIcon={
<Icon
name='mail'
size={24}
/>
}
value={email}
onChangeText={setEmail}
/>
</View>
<View style={styles.subContainer}>
<Button
style={styles.textInput}
icon={
<Icon
name="input"
size={15}
color="white"
/>
}
title="Reset"
onPress={() => reset()} />
</View>
<View style={styles.subContainer}>
<Button
style={styles.textInput}
icon={
<Icon
name="check-circle"
size={15}
color="white"
/>
}
title="Back to Login"
onPress={() => {
navigation.navigate('Login');
}} />
</View>
{showLoading &&
<View style={styles.activity}>
<ActivityIndicator size="large" color="#0000ff" />
</View>
}
</View>
</View>
);
Finally, add these styles for this Reset Form after the navigationOptions.
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
formContainer: {
height: 400,
padding: 20
},
subContainer: {
marginBottom: 20,
padding: 5,
},
activity: {
position: 'absolute',
left: 0,
right: 0,
top: 0,
bottom: 0,
alignItems: 'center',
justifyContent: 'center'
},
textInput: {
fontSize: 18,
margin: 5,
width: 200
},
})
The Home screen is the initial screen that comes first when this React Native app started. So, there will be a function to check the authenticated user. If it exists then this screen will display the user email. If not exists, it will be redirected to the Login screen. Open and edit components/Home.js
then add/replace these imports of required elements and Firebase auth.
import React, { useState, useEffect } from 'react';
import { View, Text } from 'react-native';
import { Button, Icon } from 'react-native-elements';
import auth from '@react-native-firebase/auth';
Add these required useState constant variables inside the first line of the Home function body.
const [initializing, setInitializing] = useState(true);
const [user, setUser] = useState();
Add a function that sets the user value if the user authenticated.
function onAuthStateChanged(user) {
setUser(user);
if (initializing) setInitializing(false);
}
Add the useEffect function check the authenticated user every time the screen loaded.
useEffect(() => {
const subscriber = auth().onAuthStateChanged(onAuthStateChanged);
return subscriber; // unsubscribe on unmount
}, []);
Add a condition that returns null user if initializing is true.
if (initializing) return null;
Add a condition that redirects to the Login page if there’s no user exists or loaded.
if (!user) {
return navigation.navigate('Login');
}
Modify the view to implementing the user email on this screen.
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Welcome {user.email}</Text>
</View>
);
Finally, modify the navigationOptions to add the logout button that fires the logout method of Firebase auth.
Home.navigationOptions = ({ navigation }) => ({
title: 'Home',
headerRight: () => <Button
buttonStyle={{ padding: 0, marginRight: 20, backgroundColor: 'transparent' }}
icon={
<Icon
name="cancel"
size={28}
color="white"
/>
}
onPress={() => {auth().signOut()}} />,
});
This time to run and test the React Native Firebase Email login app in the iOS simulator and Android device. To run this app to the iOS device, you need an XCode Signing Development Team. For iOS, type this command.
react-native run-ios
When the new terminal windows open, type this command immediately.
cd ~/Apps/RNEmailAuth && yarn start
To run in an Android device, make sure the Android phone connected to the computer and available by this command.
adb devices
Next, run to the android device by type this command.
react-native run-android
When the new terminal windows open, type this command immediately.
cd ~/Apps/RNEmailAuth && yarn start
And here they are the fully working React Native Firebase Authentication Email/Password.
You also can check the registered email in the Firebase console like this.
And the received password reset email link should be similar to this.
That it’s, the React Native Tutorial: Firebase Email Login Example. You can get the full source code in our GitHub.
Thanks!
#react-native #react #ios #react-js