Understand to Use Portal and Error Boundary in React

Understand to Use Portal and Error Boundary in React

In this article, we will learn about React Portal and Error Boundary and how it can be used in React.

In this article, we will learn about React Portal and Error Boundary and how it can be used in React.

Portal

A React Portal is a way of binding an element outside of its component hierarchy, in a separate component. The name Portal represents that an element can be set anywhere in the DOM tree that’s outside of the normal React components tree. The concept of Portal is added after version 16.0 in React.

React provides an API to create portal named ReactDOM.createPortal() that accepts 2 parameters, the first parameter is an element which needs to be rendered and the second element is the DOM element in which it needs to be rendered. Portals are mostly used for implementing, Tooltip, Modals, Global message notifications, hovercards, chat widgets, and Floating menus. For Portal, we can return strings, numbers, components, React portals or an array of children.

Event Bubbling through React Portals

As React portal can be anywhere outside of DOM tree but it will act like a React child in all other ways, despite the fact that a child is a portal, it will still exist in the React tree regardless of its position in the DOM tree. So, if we want to trigger any event from the Portal, it will propagate to ancestors in the containing tree, even if those elements are not ancestors of the DOM tree.

Let’s look at the demo that will display tooltip using Portal.

import React, { Component } from 'react'    
    
class Tooltip extends Component {    
  constructor(props) {    
    super(props)    
    this.state = { hover: false }    
  }    
      
  handleMouseIn() {    
    this.setState({ hover: true })    
  }    
      
  handleMouseOut() {    
    this.setState({ hover: false })    
  }    
      
  render() {    
    const tooltipStyle = {    
      display: this.state.hover ? 'block' : 'none'    
    }    
        
    return (    
    
      <div>    
        <div onMouseOver={this.handleMouseIn.bind(this)} onMouseOut={this.handleMouseOut.bind(this)}>on hover here we will show the tooltip</div>    
        <div>    
          <div style={tooltipStyle}>this is the tooltip!!</div>    
        </div>    
      </div>    
    );    
  }    
}    
    
export default Tooltip     

Now, use the Tooltip component in the App component.

import React from 'react';    
import logo from './logo.svg';    
import './App.css';    
import Tooltip from "./components/Tooltip"    
    
function App() {    
  return (    
    <div>    
      <header>    
        <img src={logo} className="App-logo" alt="logo" />                  
      </header>          
      <div>    
        <Tooltip>Hello World !</Tooltip>    
      </div>    
    </div>    
  );    
}    
    
export default App;  

The output will be displayed as below.

So, in this way, we can also customize a component for extra functionalities like creating models, Tooltip, etc.

Error Boundary

In React, there is a concept for Error Boundary that prevents the errors being thrown to the user. So, if any error occurs, this will display a user-friendly view. This Error Boundary component is a component that catches JavaScript errors from their child component trees, log those errors, and display a fallback UI in place of the component tree crashed errors thrown by the application. Error Boundaries catch errors during rendering, in lifecycle methods, and in constructor inside the whole trees. Error Boundaries are created as a class boundary when any one or both of these methods are defined -  static getDerievedStateFromError() or componentDidCatch().

The above 2 error methods are used to catch error UI and log error information respectively.

static getDerievedStateFromError()

This method is invoked after an error is thrown by the child component. It gets the error thrown by the child component as a parameter and it should return the value to update state.

The below code is a basic syntax to use Error Boundary.

import React,{Component} from 'react';    
    
class ErrorBoundary extends Component{    
    constructor(props) {    
        super(props)    
        
        this.state = {    
            hasError : false    
        }    
    }    
    
    static getDerivedStateFromError(error){    
        return {hasError:true};    
    }    
    
    render(){    
        if(this.state.hasError){    
            return <h2>Error Occurred</h2>                
        }    
        return this.props.children;    
    }    
}    
    
export default ErrorBoundary    

As the getDerievedFromState() method is called during the render phase just to set the state in React, so it does not involve any side effects. So, for that, we need to use the componentDidCatch() method.

componentDidCatch()

This method is used to log error information thrown during the getDerievedFromState() method.

Syntax - componentDidCatch(error,info)

import React,{Component} from 'react';    
    
class ErrorBoundary extends Component{    
    constructor(props) {    
        super(props)    
        
        this.state = {    
            hasError : false    
        }    
    }    
    
    static getDerivedStateFromError(error){    
        return {hasError:true};    
    }    
    
    componentDidCatch(error,info){    
      // Any reporting Service of custom code to set state    
    }    
        
    render(){    
        if(this.state.hasError){    
            return <h2>Error Occurred</h2>                
        }    
        return this.props.children;    
    }    
}    
    
export default ErrorBoundary   

The lifecycle is invoked when an error is thrown from a child component. It takes 2 parameters.

error - The error that was thrown

Info - An object with ComponentStack key containing information about which component threw the error.

componentDidCatch() is called during commit phase, so side effects are permitted and used for logging errors.

Some important point to keep in mind while using Error Boundary,

  1. Error boundaries do not catch error in below cases,
  2. Thrown in error boundary itself.
  3. Event handlers
  4. for Async Code
  5. Server Side rendering
  6. Only class components can be error boundaries
  7. Error boundaries work like javascript catch {} block, but just for a component.

Let’s see a demo for Error Boundary.

ErrorBoundary.js

import React,{Component} from 'react';    
    
class ErrorBoundary extends Component{    
    constructor(props) {    
        super(props)    
        
        this.state = {    
            hasError : false    
        }    
    }      
    static getDerivedStateFromError(error){    
        return {hasError:true};    
    }      
    componentDidCatch(error,info){    
        this.setState({    
            hasError:true    
        })    
    }          
    render(){    
        if(this.state.hasError){    
            return <h2>Error Occured</h2>                
        }    
        return this.props.children;    
    }    
}      
export default ErrorBoundary    

Just change a method name to generate error in Tooltip.js

import React, { Component } from 'react'      
class Tooltip extends Component {    
  constructor(props) {    
    super(props)    
    this.state = { hover: false }    
  }        
  handleMouseIn() {    
    this.setState({ hover: true })    
  }        
  handleMouseOut() {    
    this.setState({ hover: false })    
  }        
  render() {    
    const tooltipStyle = {    
      display: this.state.hover ? 'block' : 'none'    
    }    
    return (      
      <div>    
        <div onMouseOver={this.handleMouseIn.bind(this)} onMouseOut={this.handleMouseOut1.bind(this)}>on hover here we will show the tooltip</div>    
        <div>    
          <div style={tooltipStyle}>this is the tooltip!!</div>    
        </div>    
      </div>    
    );    
  }    
}      
export default Tooltip    

Now in App.js file

import React from 'react';    
import logo from './logo.svg';    
import './App.css';    
import Tooltip from "./components/Tooltip"    
import ErrorBoundary from "./components/ErrorBoundary"    
    
function App() {    
  return (    
    <ErrorBoundary>    
    <div>    
      <header>    
        <img src={logo} className="App-logo" alt="logo" />                  
      </header>          
      <div>    
        <Tooltip>Hello World !</Tooltip>    
      </div>    
    </div>    
    </ErrorBoundary>    
  );    
}    
    
export default App;    

The output will be displayed as below,

Here you will note a change. After displaying the above screen just after a few seconds error page is displayed again as below,

This is because in development phase Error Boundaries do not override error overlay. Which may not happen in the production phase. To resolve this issue you can add below code in your CSS file.

iframe {    
  display: none;    
}  

Then, the text or image you want to display using the error boundary will remain on browser's screen.

Summary

In this article, we have learned about Portals and Error Boundary in React.

Thank you for reading !

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

What’s new in HTML6

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

React Tutorial for Beginners - Learn React in 1 Hour

React Tutorial for Beginners - Learn React in 1 Hour

React Tutorial for Beginners - Learn React in 1 Hour. The quick guide to learn basic concepts and workflow of how to build React App. In this course you will learn React in 1 hour. You will learn what react does, you will learn how react works, you will learn views, components, state, routing, react lifecycle and much more.

React is not complicated as it seems and you can learn it quickly.

In this course you will learn React in 1 hour. This is not a code along and the styling is not important. The important things are - You will learn what react does, you will learn how react works, you will learn views, components, state, routing, react lifecycle and much more. You dont need 14 hours to learn react.

This course is 1 hour long and it will probably take you from 1 - 3 hours to finish it in a sense where you will understand what React does and how it works.

React State Management Tutorial - Context API

React State Management Tutorial - Context API

In this React tutorial for beginners, we are going to learn everything about state management in React. The reason you might need a state management tool like the Context API or Redux. We will focus on learning to context api today together with react hooks which is a new modern way of writing react code. The context api provides us with useful hook called useContext that lets us use a state in any of our components we want!

In this episode we are going to learn everything about state management in React.

The reason you might need a state management tool like the context api or redux, is to be able to share state between all your components in your react project.

We will focus on learning to context api today together with react hooks which is a new modern way of writing react code. The context api provides us with useful hook called useContext that lets us use a state in any of our components we want!

React Native Tutorial: Using Firebase Email Authentication or Login

React Native Tutorial: Using Firebase Email Authentication or Login

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. We will use the latest React Hooks and React Native Firebase library to develop this login app. A comprehensive step by step React Native tutorial on authentication or login using Firebase email authentication.

A comprehensive step by step React Native tutorial on authentication or login using Firebase email authentication

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.

This tutorial divided into several steps:

  • Step #1: Setup Google Firebase Email Authentication
  • Step #2: Create a New React Native Apps
  • Step #3: Install and Configure React Native Firebase
  • Step #4: Add React Navigation Header and Pages
  • Step #5: Implementing Firebase Email Login
  • Step #6: Implementing Firebase Email Register
  • Step #7: Implementing Firebase Email Reset Password
  • Step #8: Implementing a Secure Home Screen
  • Step #9: Run and Test React Native Firebase Email 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:

  1. Node.js (NPM or Yarn)
  2. React Native
  3. Google Firebase
  4. React Native Firebase library
  5. Android Studio or SDK for Android
  6. XCode for iOS
  7. Terminal (OSX/Linux) or Command Line (Windows)
  8. Text Editor or IDE (We are using Visual Studio Code)

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
Step #1: Setup 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 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.

Step #2: Create a New React Native Apps

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
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 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];

Setup React Native Firebase on Android

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
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 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 />
  )
}
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. 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
    },
})
Step #6: Implementing Firebase Email Register

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
    },
})
Step #7: Implementing Firebase Email Reset Password

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
    },
})
Step #8: Implementing a Secure Home Screen

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()}} />,
});
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 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!