In this React Native step-by-step tutorial, we will show you an example of using Firebase email authentication or logging 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:
- Node.js (NPM or Yarn)
- React Native
- Google Firebase
- React Native Firebase library
- Android Studio or the SDK for Android
- XCode for iOS
- Terminal (OSX/Linux) or Command Line (Windows)
- Text Editor or IDE (We are using Visual Studio Code)
Before starting 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
You can watch the video tutorial on our YouTube channel. Please, like, share, comment, and subscribe to this channel.
Step #1: Set up Google Firebase Email Authentication
We have to go to the Google Firebase Console https://console.firebase.google.com/ to set up the Firebase email authentication. After logging in 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 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 pan,e then click Project Settings.
To set up iOS Apps, scroll down the Settings pane, then click the iOS icon button.
Fill in the iOS bundle ID that was registered in your Apple Developer account, then click the "Register App" button. Click the "Download GoogleService-Info.plist" button to download the configuration file for the iOS app, then click the "Next" button a 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" buttona 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.
Step #2: Create a New React Native App
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 on 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 opens, 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's ready to use with the Firebase Authentication Email/Password.
For Android a little tricky. First, change the source folders which previously were `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
Step #3: Install and Configure React Native Firebase
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
Setup React Native Firebase on iOS
To make this React Native Firebase Authentication work on iOS devices, make sure you have XCode Signing Development Team. Otherwise, you can only run this iOS app on the simulator.
Next, open the `ios/RNEmailAuth.xcworkspace` from Xcode, then add the previously downloaded GoogleService-Info.plist to the XCode project.
After adding 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 imports from the Firebase.
#import <Firebase.h>
At the beginning of the `didFinishLaunchingWithOptions:(NSDictionary *)launchOptions` method, add this line to initialize Firebase.
[FIRApp configure];
Set up React Native Firebase on Android
Copy the previously downloaded google-services.json to the `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's all, configuration was auto-linked when adding @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
Step #4: Add React Navigation Header and Pages
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 code and disable the 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 code and disable the 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 code.
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 code and disable the 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 app. For that, add the libraries of React Navigation and React Native Gesture Handler by typing 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 initializes 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 />
)
}
Step #5: Implementing Firebase Email Login
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. The Register and Reset button will redirect to the 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 work on iOS, open and edit `ios/RNEmailAuth/Info.plist`, then add these lines of UIAppFonts before the end of </dict>.
<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 implement 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 style 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
},
})
Step #6: Implementing Firebase Email Register
The Firebase authentication email password register or sign-in is almost the same as the previous Login. The difference is 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
},
})
Step #7: Implementing Firebase Email Reset Password
The reset password screen just required one email input text and a 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 password reset to Firebase authentication. The Firebase will send the reset link email to the email address that is used 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 the view for the 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
},
})
Step #8: Implementing a Secure Home Screen
The Home screen is the initial screen that comes first when this React Native app starts. So, there will be a function to check the authenticated user. If it exists, then this screen will display the user's email. If not exist, 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 is authenticated.
function onAuthStateChanged(user) {
setUser(user);
if (initializing) setInitializing(false);
}
Add the useEffect function to check the authenticated user every time the screen loads.
useEffect(() => {
const subscriber = auth().onAuthStateChanged(onAuthStateChanged);
return subscriber; // unsubscribe on unmount
}, []);
Add a condition that returns a 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 is loaded.
if (!user) {
return navigation.navigate('Login');
}
Modify the view to implement the user's 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()}} />,
});
Step #9: Run and Test React Native Firebase Email Login App
This time to run and test the React Native Firebase Email login app in the iOS simulator and an Android device. To run this app on an 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 on an Android device, make sure the Android phone is connected to the computer and available with this command.
adb devices
Next, run to the Android device by typing 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 can also check the registered email in the Firebase console like this.
And the received password reset email link should be similar to this.
That's the React Native Tutorial: Firebase Email Login Example. You can get the full source code on our GitHub.
That's just the basics. If you need more deep learning about React.js, React Native, or related, you can take the following cheap course:
- Master React Native Animations
- Advanced React Native Topics
- React Native
- Learning React Native Development
- React: React Native Mobile Development: 3-in-1
Thanks!